skip to Main Content

I have a function in React Native which calls the Google Routes API. I got the expected response when debugging inside the function but when I try to store the information returned by the API inside a variable, variable shows undefined. How can I fix this?

Code:

async function computeDuration(currentLocation, targetLocation, travelMode, routingPreference){
    const apiKey = config.GOOG_ROUTES_API_KEY; 
    const requestBody = {
      origin: {
        location: {
          latLng: {
            latitude: currentLocation.coords.latitude,
            longitude: currentLocation.coords.longitude,
          },
        },
      },
      destination: {
        location: {
          latLng: {
            latitude: targetLocation.latitude,
            longitude: targetLocation.longitude,
          },
        },
      },
      travelMode: travelMode,
      routingPreference: routingPreference, 
      computeAlternativeRoutes: false,
      routeModifiers: {
        avoidTolls: false,
        avoidHighways: false,
        avoidFerries: false,
      },
      languageCode: "en-US",
      units: "METRIC",
    };

    fetch("https://routes.googleapis.com/directions/v2:computeRoutes", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Goog-Api-Key": apiKey,
        "X-Goog-FieldMask":
          "routes.duration,routes.distanceMeters",
      },
      body: JSON.stringify(requestBody),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => {
        // Handle the response data here
        console.log(data);
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  }

const getAPIData = () => {
    data = computeDuration(location, { latitude, longitude }, "DRIVE", "TRAFFIC_AWARE")
    console.log("This is api data:", data)
  };

2

Answers


  1. As I see, you use the async function and when we call the async function you must await the result of that function.

    Fix this:

    wrong way >

     const getAPIData = () => {
        data = computeDuration(location, { latitude, longitude }, "DRIVE", "TRAFFIC_AWARE")
        console.log("This is api data:", data)
      };
    

    correct way >

    const getAPIData = async () => {
        data = await computeDuration(location, { latitude, longitude }, "DRIVE", "TRAFFIC_AWARE")
        console.log("This is api data:", data)
      };
    
    Login or Signup to reply.
  2. The response from computeDuration function should be returned and await should be used to get it from computeDuration function.

    const getAPIData = async () => {
        data = await computeDuration(location, { latitude, longitude }, "DRIVE", "TRAFFIC_AWARE")
        console.log("This is api data:", data)
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search