0

I was working with an api meaning that I fetch the api and convert it to json before i pass it to one of the state i want to update.

It was working fine until it didn't.

const [ids, setIDs] = useState([]);

This is the code for fetching from the api

const fetchData = async () => {
      //setting up the video ids
      const res = await fetch("http://localhost:3000/videosid");
      const jsonRes = await res.json();
      setIDs(jsonRes);
      //setting up the local database
      console.log("Fetching data from youtube...");

      console.log("ids:", ids);
      localStorage.setItem("VideosID", ids);
    };

when I console.log the values of res and jsonRes everything shows up, but for some reason it does not update the state.

Any ideas why ?

EDIT

I would also like to say that when doing the same with a local json file the state updates immediately.

const localfetchData = () => {
      //setting up the video ids
      setIDs(jsonfile);
      //setting up the local database
      localStorage.setItem("VideosID", ids);
    };
Raha32
  • 1
  • 3

2 Answers2

0

setState is an asyncronous function so sometimes it takes time to update the state. So one solution you can try is console logging the values and setting it in localStorage after the function call.

const fetchData = async () => {
  //setting up the video ids
  const res = await fetch("http://localhost:3000/videosid");
  const jsonRes = await res.json();
  setIDs(jsonRes);
  //setting up the local database
  console.log("Fetching data from youtube...");
};

fetchData()
console.log("ids:", ids);
localStorage.setItem("VideosID", ids);
Dharmik Patel
  • 1,041
  • 6
  • 12
0

setState actions are asynchronous and are batched for performance gains. So if you need to ensure ordering of events after a setState call is made, you can pass a callback function

const fetchData = async () => {
      //setting up the video ids
      const res = await fetch("http://localhost:3000/videosid");
      const jsonRes = await res.json();
      setIDs(jsonRes, () => { 
                               console.log("ids:", ids);
                               localStorage.setItem("VideosID", ids);
                            });
     
       };

Or you can add useEffect function with a dependency on state.

 useEffect(() =>
 {
     console.log("ids:", ids);
     localStorage.setItem("VideosID", ids);
 }, [ids]);

 const fetchData = async () => {
  //setting up the video ids
  const res = await fetch("http://localhost:3000/videosid");
  const jsonRes = await res.json();
  setIDs(jsonRes);

 };
user1672994
  • 10,509
  • 1
  • 19
  • 32