Home > Net >  What is the best way to handle data from a .then outside of the .then?
What is the best way to handle data from a .then outside of the .then?

Time:07-30

I am using google's geocoding api to convert an address into a coordinate.

I have the following fetch to accomplish that.

    fetch(
    `https://maps.googleapis.com/maps/api/geocode/json?address=${prop.address}&key=${
      getEnv().APP_PUBLIC_GOOGLE_API_KEY
    }`
  )
    .then((response) => response.json())
    .then((data) => console.log(data.results[0].geometry.location));

This successfully console logs the objects that I want to extract from this json.

What I want to know is: How do I use this object within the rest of my code?

For context this code is within a react component

Context

And I want to use the coordinate object I get back inside of the <GoogleMap/> component's center prop and the <Marker/> component's position prop.

CodePudding user response:

You can make use of the hooks useState to store the data and useEffect to operate on it. You'll probably want something along the lines of:

function MyComponent(props) {
  [ data, setData ] = useState(null);
  
  let fetchData = () => {
    fetch(
      `https://maps.googleapis.com/maps/api/geocode/json?address=${props.address}&key=${
      getEnv().APP_PUBLIC_GOOGLE_API_KEY
    }`
    )
    .then((response) => response.json())
    .then((data) => setData(data));
  };
  
  useEffect(() => {
    if (data === null) return;
    
    // do stuff with `data`
    console.log(data.results[0].geometry.location)
  }, [data]);
  
  // rest of your component
}

CodePudding user response:

Quick answer: You can't.

So maybe there is a workaround?

Yes

Here it is:

(async function(){
let response = await fetch(
    `https://maps.googleapis.com/maps/api/geocode/json?address=${prop.address}&key=${
      getEnv().APP_PUBLIC_GOOGLE_API_KEY
    }`
  )
response = await response.json()
//and then you can use response in the rest of your code I mean inside of the async function. If you are using node.js, and import node-fetch, then you can just do it without the async function. 
})()
  • Related