useState react hook does not set the array state

Viewed 1179

I am trying to set the videos state to the items array of the response from the api but when I console.log the videos it returns an empty array.... Here is the code to fetch the api in which I set the videos state

const [videos, setVideos] = useState([]);
const handleFormSubmit = async (searchterm) => {
    await fetch(
      `https://www.googleapis.com/youtube/v3/search?${params.toString()}&q=${searchterm}`
    )
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        setVideos(data.items);
        console.log(videos);
      });
  };

How do I set the items array to the videos state?

3 Answers

Ciao, unfortunately with hooks you cannot log videos after setVideos call because setVideos is async.

To get the last value of videos you have to use useEffect hook in this way:

useEffect(() => {
   console.log(videos);
}, [videos]);

You are using async/await, so it should be

const [videos, setVideos] = useState([])
const handleFormSubmit = async (searchterm) => {
  const response = await fetch(
    `https://www.googleapis.com/youtube/v3/search?${params.toString()}&q=${searchterm}`
  )
  const data = await response.json()
  console.log(data)
  setVideos(data.items)
  console.log(videos)
}
Related