1

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

2 Answers2

4

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]);
2

If u want you can try like this;

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

    setIsLoaded(true);
    setBootcamps(data);
  };



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

Because your dependacy missing and i dont know your data type but your data is a object maybe if u want try;

const [bootcamps, setBootcamps] = useState({});
aaliakinci
  • 262
  • 1
  • 2
  • 8