'Problems with axios and useState in React App [duplicate]

I'm trying to fetch data with axios, I use console.log and it's seem worked fine. But when I try to set it to my state, it's return an empty array. I'm tried to searching my problem but have no luck. Any idea?

import React, { useState } from 'react';
import axios from 'axios';
import Error from '../components/Error';

export const PhotoContext = React.createContext();

const apiKey = '636e1481b4f3c446d26b8eb6ebfe7127';

const PhotoContextProvider = (props) => {
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState<boolean>(false);
  const runSearch = (query) => {
    axios
      .get(
        `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&tags=${query}&per_page=24&format=json&nojsoncallback=1`
      )
      .then((response) => {
        setImages(response.data.photos.photo);
        setLoading(false);
        console.log(images); //return an empty array
        console.log(response.data.photos.photo); // return an object as it should be
      })
      .catch((err) => {
        return <Error />;
      });
  };
  return (
    <PhotoContext.Provider value={{ images, loading, runSearch }}>
      {props.children}
    </PhotoContext.Provider>
  );
};

export default PhotoContextProvider;

Here's my full code on stackblitz: https://stackblitz.com/edit/react-ts-hhqiwr?file=context%2FPhotoContext.tsx



Solution 1:[1]

The problem is, setting of state is async, if you console.log images after using setImages, it will return the old value.

The correct way is to use useEffect to monitor changes.

useEffect(() => {

  console.log('images', images) //new value will be reflected

},[images])

I've checked your codesandbox and it is setting the state correctly for response.data.photos.photo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Someone Special