Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When setting state with React's use state hook using it's prev (or initial) value throws an error Type Error 0 is not a function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 <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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading