Home > other >  Getting undefined value in useEffect (React)
Getting undefined value in useEffect (React)

Time:05-28

The below function gets the current location of a user:

  const getCurrentLocation = () => {
    fetch("https://ipinfo.io/json?token=$TOKEN")
      .then((response) => response.json())
      .then((jsonResponse) => {
        console.log(jsonResponse)
        return jsonResponse;
      });
  };
  useEffect(() => {
    console.log(getCurrentLocation());
    }, []);  

logging in useEffect is showing undefined and it is appearing first in the console, then jsonResponse shows next in the console with the corresponding object. Why is that ?

CodePudding user response:

getCurrentLocation doesn't return anything, that's why you got undefined.

Moreover, fetch returns a Promise, which is asynchronous, meaning you don't get the result immediately, you must pass a calback to then to get the result when it is available.

const getCurrentLocation = () => {
  return fetch("https://ipinfo.io/json?token=$TOKEN")
    .then(response => response.json());
};

useEffect(() => {
  getCurrentLocation()
    .then(location => console.log(location));
}, []);  

CodePudding user response:

The getCurrentLocation function is not returning anything. Try saving the location in the state, so that you can access it when needed:

const [currentLocation, setCurrentLocation] = useState(null);

const getCurrentLocation = () => {
  fetch("https://ipinfo.io/json?token=$TOKEN")
    .then((response) => response.json())
    .then((jsonResponse) => {
      setCurrentLocation(jsonResponse); // <- save the location in state
    });
};

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

return <div>{currentLocation}</div>

If you need the location in a useEffect, you could do:

useEffect(() => {
  if (currentLocation !== null) {
    // ...
  }
}, [currentLocation])

CodePudding user response:

you can simply use async/await to get response, take a look at this one:

 const getCurrentLocation = async () => {
    const result = await fetch("https://ipinfo.io/json?token=$TOKEN");
    return result.json();
  };



 const handleGetLocation = async () => {
   const result = await getCurrentLocation();
   console.log(result);
  };

  useEffect(() => {
    handleGetLocation();
  }, []);
  • Related