I am completely new to ReactJS. Please be kind, I really could not find an answer to my problem.
In useEffect I update my variable (which is an array of objects) and in my onClick function I want to update my variable again.
Since useEffect runs after I create my onClick function, my variable is still empty on onClick. I need to be able to access my updated variable in my onClick function.
How can I update my variable in useEffect first, before I create my onClick function?
const [myvariable, setMyvariable] = useState([{}]);
useEffect({
setMyVariable([{
id: 1
}]);
}, []);
const onClick = () => {
// update my variable here
setMyVariable(prev => [...prev, {name: 'My name'} ]); // <-- Code here is probably not correct but you get the idea.
// prev is an empty object at this point since useEffect has not run yet
}