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?
setVideosis not a synchronous operation, the videos array will change the next time the functional component is rendered.setVideos. Your state is getting updated, your component will have to re-render to see the updated state. Also make sure you have acatchblock to catch and handle any errors that might occur during the request.async-awaitsyntax or promise chaining, don't mix both of them.