0

I am new to reactjs and have written the below code which fetches the location data and has to set in the locationData variable using useState hook - the data is being fetched and able to console.log(result) but setLocation is not working - when I print it it's just blank. I just tried setLocation by entering manual data setLocation({"status":"OK"}) - even that is not working, kindly help

const [locationInfo, setLocationInfo] = useState(null)
    const [locationData, setLocationData] = useState({})
    const [loading, setLoading] = useState(false)
    const [locationPage, setlocationPage] = useState("hospitals")

    useEffect(() => {
        console.log(props.uuid)
        async function fectLocations() {
          setLoading(true)
          const response = await fetch(`http://127.0.0.1:8000/api/prop/${uuid}`)
          const result = await response.json();
          console.log(result)
          setLocationData(result)
          setLoading(false)
          console.log("locsation" + JSON.stringify(locationData))
        }
    
        fectLocations()
        console.log("locsation" + JSON.stringify(locationData))
        console.log("locsation" + locationData)
      }, [])
    
  • Calling setLocationData doesn't change the values in any local variables, it just instructs react to rerender the component. So your log statement isn't in a useful spot, because nothing can have changed. If you want to verify that the component rerenders, put a log statement in the body of the component (ie, outside the useEffect) – Nicholas Tower Oct 23 '21 at 18:30

0 Answers0