SetState doesn't work with with data from server

后端 未结 1 411
眼角桃花
眼角桃花 2020-12-21 19:06

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

相关标签:
1条回答
  • 2020-12-21 19:53

    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>

    0 讨论(0)
提交回复
热议问题