I’m using a very basic setup of providers. I’m sure my component is wrapped within the provider and the value should be passed to the child component.
const { totalData } = useContext(Context);
const [setTotal] = totalData;
I’m extracting a set method here to set a total cost of selected items. and on my Provider side
const [total, setTotal] = useState(0);
and I’m exposing this state like so
<Context.Provider
value={{
totalData: [total, setTotal],
}}>
{props.children}
</Context.Provider>
when a button is pressed in this case a React Native TouchableOpacity I’m setting the state like so;
setTotal(prev => checked ? prev + item.total_cost : prev - item.total_cost)
any ideas on how this might happen is really appreciated.
Thanks!!
>Solution :
You’re using arrays to store your value and setter function where you’re setting total as the first value (index 0) and setTotal as the second value (index 1).
The problem with this is when you write const [setTotal] = totalData; you are actually grabbing the first value in the totalData array (which is total) and renaming it as setTotal.
So now you’re trying to call setTotal() but you’re effectively writing total() which gives you that error.
Solution:
It would be a better developer experience to store these values as keys in an object so that you can destructure them the way you want to.
Change you context provider this:
<Context.Provider value={{ totalData: { total, setTotal } }}>
{props.children}
</Context.Provider>
Then use it like this:
const { totalData } = useContext(Context);
const { setTotal } = totalData;
Note:
If you really want to keep using arrays like you originally have been doing this, then you can destructure it like this:
const [_, setTotal] = totalData;
// Or
const setTotal = totalData[1];
This way you are grabbing the second item in your array (the set function), and simple ignoring the first (total) value.