Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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(() => {
  ...
}, [])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading