Home > Blockchain >  React cannot setState in useEffect
React cannot setState in useEffect

Time:05-18

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

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

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

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.

CodePudding user response:

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.

CodePudding user response:

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);
  }, [])

This is the code when I add console.log in get function and after get function. this is the results

  • Related