I am trying to fetch images from an Unsplash API, and then trying to update the images data using useState in the following code.
const [images, setImages] = useState([]);
useEffect(() => {
Axios.get(
"https://api.unsplash.com/photos/?client_id=l2U-D_PXXujBJoRiCCMCL2ifi_5ZJcK4AC0WH-A2lKk"
)
.then((res) => {
//res.data is printing correct/expected value
console.log(res.data);
setImages(res.data);
console.log("lul");
//but images array is still empty
console.log("images: ", [images]); // []
})
.catch((err) => console.error(err));
}, []);
If I put the images array in the dependency array, then I am able to update the image array, but then fetching is occurring infinitely.
Why this is happening?
What you are doing wrong is that your are trying to console.log before React has re-rendered. Updating a state through the related setState is not instantaneous, it's an asynchronous task. A re-render is needed to get the updated value. See the code below, I added comments.
Also it's a bad idea to put
imagesin the dependencies' array, you will get an infinite loop.
const [images, setImages] = useState([]);
console.log("images: ", [images]); // you get [] for the first time, and after state change and re-render, it will contains the fetched data.
useEffect(() => {
Axios.get(
"https://api.unsplash.com/photos/?client_id=l2U-D_PXXujBJoRiCCMCL2ifi_5ZJcK4AC0WH-A2lKk"
)
.then((res) => {
setImages(res.data);
})
.catch((err) => console.error(err));
}, []);
setState is invoked asynchronous (though is doesn't return a promise so you can't await it).
Keep your useEffect as it is now, and in order to print the new value whenever the images changes, you can use another useEffect:
useEffect(() => {
console.log("images: ", [images]); // []
}, [images]);