What you are doing wrong is that you are trying to console.log
before React has re-rendered. Updating a state
through the related setState
is not instantaneous as the doc says:
The
set
function only updates the state variable for the next render. If you read the state variable after calling the set function, you will still get the old value that was on the screen before your call.
One way to log changes in your state is to add a console.log()
just after defining it:
const [images, setImages] = useState([]);
// It logs [] the first time and then the fetched data
console.log(images);
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));
}, []);