Reputation: 1317
I am fetching images from the server. Why the console.log(images) inside the useEffect is a empty array, but outside the useEffect it return the data.
const ImageGrid = () => {
const [images, setImages] = useState([]);
useEffect(() => {
fetch(`https://api.unsplash.com/photos/?client_id=${key}&per_page=28`)
.then(res => {
return res.json();
})
.then(images => {
setImages(images);
});
console.log(images);
}, []);
console.log(images);
return (
<div className="content">
<section className="grid">
{images.map(image => (
<div>
<img src={image.urls.small} alt={image.user.username} />
</div>
))}
</section>
</div>
);
};
Upvotes: 0
Views: 94
Reputation: 1004
First thing you need to know API calls are asynchronous. And return value of them is a promise.
So in your example inside useEffect
you are calling API using fetch
so basically it is asynchronous. and once API call is finished depending on returned promise state it calls then
block or catch
block.
If promise gets successfully resolved then it calls then
block else if promise gets rejected then it goes into catch
block.
Now your console.log
inside useEffect
is not logging the data because it will get executed immediately after the call to API and it does not wait for API response to get back.
And outside console.log
is logging the data because after response is returned inside then
block you are calling setImages
so after calling this your function component get re-rendered this causes your second console.log
to print data.
See this for references -
Upvotes: 1