Skip to content
Advertisement

.push( ) is not updating the variable

I am trying to push the data that is set using setData function to datas[ ]. I am able to push the data once, but the 2nd time when I push it, instead of being stored at datas[1], it replaces datas[0]. What am I doing wrong here. Thank you in advance.

JavaScript

Advertisement

Answer

App is getting re-rendered whenever you change states, so const datas=[]; will be initialized as a new array.

One more problem I can foresee is that you call setData(day) and then call datas.push(data) on the same function which won’t be applied with your latest data because states’ changes are asynchronous

JavaScript

The full modification can be

JavaScript

You also should not use useEffect with setters (setData and setName). These setters have nothing to do with side-effects. You should pass state values as dependencies in useEffect.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement