'React cannot setState in useEffect

const [soilInfo, setSoilInfo] = useState([]);
  const [ambient, setAmbient] = useState([])

  useEffect(() => {
    const getSoil = () => {
      axios.get("http://localhost:8081/soil_info").then((response) => {
        setSoilInfo(response.data);
        console.log(response.data);
      })
    }
    getSoil();
    console.log(soilInfo);
  },[])

  useEffect(() => {
    const getAmbient = () => {
      axios.get("http://localhost:8081/ambient").then((response) => {
        setAmbient(response.data);
        console.log(response.data);
      })
    }
    getAmbient();
    console.log(ambient);
  }, [])

I tried debugging by printing in get function and after get function. It turns out that soilInfo and ambient are null sets. The response was fine. This is the results



Solution 1:[1]

I have a couple of ideas here:

  1. Your axios get call could be failing. This would result in your then clause not being called. I would try logging out the response or adding a catch clause to verify the request is working.

  2. Both setSoilInfo and setAmbient are expecting a list at the moment (if you are using Typescript at least). What data type is response.data? If you know, I'd recommend typing your useState like so: useState<TYPE[]>. Then you can get some type help.

Let me know if you have questions about either of the above.

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 Jimmy Cerone