Search code examples
reactjsreact-hooksfetch-apisetstateuse-effect

problem in useEffect hook to fetch api in React.js


This is bootcamp.js file in react project

import React, { Component, useState, useEffect } from 'react';

const Bootcamps = () => {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [bootcamps, setBootcamps] = useState();

  const loadData = async () => {
    const response = await fetch('http://localhost:5000/api/v1/bootcamps');
    const data = await response.json();

    setIsLoaded(true);
    setBootcamps(data);
    console.log(data);      // showing data
    console.log(bootcamps); // showing undefined
  };

  useEffect(() => {
    loadData();
  }, []);

........
......
...

the console.log(bootcamps) is showing undefined. Plzz help


Solution

  • setBootcamps is asynchronous, so you cant see the result immediatly after the setter function gets called.

    You can add another useEffect with the bootcamps state as a dependency. So, when bootcamps change (after the state is set) you do something.

      useEffect(() => {
        console.log({ bootcamps });
      }, [bootcamps]);