Home > Blockchain >  Why does my axios request print in console but doesn't set state
Why does my axios request print in console but doesn't set state

Time:03-01

I'm trying to display some data from my database in my React component but the data isn't getting saved in the state hook, but the request's response does print in the console.

How can I fix this?

const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [collections, setCollections] = useState([]);

useEffect(() => {
  const getCollections = async () => {
    try {
      const response = await axios.get('http://localhost:4000/api/collections');
      setIsLoaded(true);

      console.log(response); // This prints the response
      setCollections(response);
      console.log(collections); // This prints []

    } catch (error) {
      setError(error);
      setIsLoaded(true);
    }
  }

  getCollections();
}, [])

Console logs

CodePudding user response:

setCollections is not executed immediately by React. The new state should be available on the next render. Try logging during the render phase:

const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [collections, setCollections] = useState([]);

console.log(collections);

useEffect(() => {
  ...
}, [])
  • Related