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(
`?${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?
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./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?
Share Improve this question asked Aug 12, 2020 at 10:53 prem kulkarniprem kulkarni 293 bronze badges 3-
1
setVideos
is not a synchronous operation, the videos array will change the next time the functional ponent is rendered. – Rustam D9RS Commented Aug 12, 2020 at 10:57 -
You can't log updated state right after calling
setVideos
. Your state is getting updated, your ponent will have to re-render to see the updated state. Also make sure you have acatch
block to catch and handle any errors that might occur during the request. – Yousaf Commented Aug 12, 2020 at 11:00 -
Not related to your problem but either use
async-await
syntax or promise chaining, don't mix both of them. – Yousaf Commented Aug 12, 2020 at 11:08
3 Answers
Reset to default 7Ciao, 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]);
TLDR
React Hooks work async
setState
->render
->state binding
Answer
react hooks is working like that
- setState
- schedule render ponent ( I mean state changed ponent)
- and render with changed state
So, You couldn't access video at that console.log(video)
Reference
- Overreact
- My medium with korean (You can translate with google)
- How does React Hooks re-renders a function Component?
You are using async/await
, so it should be
const [videos, setVideos] = useState([])
const handleFormSubmit = async (searchterm) => {
const response = await fetch(
`https://www.googleapis./youtube/v3/search?${params.toString()}&q=${searchterm}`
)
const data = await response.json()
console.log(data)
setVideos(data.items)
console.log(videos)
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745553199a4632672.html
评论列表(0条)