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.

export default function App() {
 const [data,setData]= useState([]);
 const [activity, setActivity]= useState([])
 const [name, setName] = useState("")

 const datas=[];
 useEffect(()=>{
  // handlePress()
 }, [setData, setName])

 const rand= Math.floor(Math.random(1,5)*4)+1
 const events=["Event A","Event B","Event C","Event D","Event E"]

 const handlePress=(day)=>{
   setData(day);
   setName(`${events[rand]}`)
   datas.push(data);
   console.log(datas);
 }
  return (
    <div className="App">
      <Calendar 
        onDayPress={day => {
          {handlePress(day)}
        }}
        
      />
      
    </div>
  );
}

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

const handlePress=(day)=>{
   setData(day); //`day` is set here but not applied immediately
   setName(`${events[rand]}`)
   datas.push(data); //data is the previous data, not `day`
   console.log(datas);
 }

The full modification can be

const datas=[]; //move your `datas` to the global scope

export default function App() {
 const [data,setData]= useState([]);
 const [activity, setActivity]= useState([])
 const [name, setName] = useState("")

 
 useEffect(()=>{
  // handlePress()
 }, [setData, setName])

 const rand= Math.floor(Math.random(1,5)*4)+1
 const events=["Event A","Event B","Event C","Event D","Event E"]

 const handlePress=(day)=>{
   setData(day); //`data` will be changed later
   setName(`${events[rand]}`)
   datas.push(day); //push `day` directly instead of data
   console.log(datas);
 }
  return (
    <div className="App">
      <Calendar 
        onDayPress={day => {
          {handlePress(day)}
        }}
        
      />
      
    </div>
  );
}

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.

//whenever `name` or `data` change, `useEffect` will be triggered
useEffect(()=>{
  //TODO: Do your logic here
 }, [data, name])
Advertisement