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>
);
}
CodePudding user response:
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])
CodePudding user response:
the datas
array is added inside the component. Everytime the component re-renders, it is re-initialized to empty array.
Also, on onDayPress
prop in the callback function you've added an extra pair of curly brackets
CodePudding user response:
In react when you update the state , react component is re-rendered . So here when you update state in handlePress() function your component is re-rendered .So your datas array is re-intialized and become empty again . So every time when you push item it will add to 1st position. Hope it will help you.