Hi I\'m programming a page with React hooks and I\'m trying to set the data I get from the server in to the state. SOmehow it doesnt work. I get the data from the server, bu
setWorkouts
is async method, so you will not get updated data right below it.
setWorkouts([...workouts, response.data])
console.log(workouts) //<--- this will not reflect the updated data
Else your code is good, it will be reflected in DOM if you are looping and showing it
Run the below code snippet and check HTML and console both, that will clear the flow.
const { useState , useEffect } = React;
const App = () => {
const [users,setUsers] = useState(['Vivek' , 'Darsh']);
useEffect(() => {
setTimeout(() => {
setUsers([...users, "Vivan" , "Darshita"]);
console.log(users);
},2000);
},[]);
return (
<div>
{ users.map(user => <p>{user}</p>) }
</div>
);
}
ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>