Home > Back-end >  state data still keeps the previous state even after setState
state data still keeps the previous state even after setState

Time:04-03

when I fetch data from my api successfully, I can display it using console.log, but somehow after I use a setState, the state still keeps the previous data. so when the page loads, the console.log(data) has an array of object containing data from the api, but console.log(rute) after the setRute still returns empty array. why is that?

this is my code

const MasterRute = () => {
  const [rute, setRute] = useState([]);

  const getRute = async () => {
    const response = await fetch('http://localhost:8080/rute');
    const data = await response.json();
    // console.log(data); // [{id:"1", name:"AAA"}, {id: "2", name: "BBB"}]
    setRute(data);
    // console.log(rute); // [] ===> why is this empty?
  }
}

any help is appreciated

CodePudding user response:

useState is asynchronous, so you won't see changes after setRute. You need to wait for the component re-rendered completely

const MasterRute = () => {
  const [rute, setRute] = useState([]);

  const getRute = async () => {
    const response = await fetch('http://localhost:8080/rute');
    const data = await response.json();
    // console.log(data); // [{id:"1", name:"AAA"}, {id: "2", name: "BBB"}]
    setRute(data);
    
  }
  
  console.log(rute); //data updated on rendering
}

You can check this article for a better understanding

If you still really want to see data after setRute. You can get the result within setTimeout

const MasterRute = () => {
  const [rute, setRute] = useState([]);

  const getRute = async () => {
    const response = await fetch('http://localhost:8080/rute');
    const data = await response.json();
    // console.log(data); // [{id:"1", name:"AAA"}, {id: "2", name: "BBB"}]
    setRute(data);
    setTimeout(() => {
       console.log(rute); //data updated
    })
  }
  
}
  • Related