简体   繁体   中英

async await resolve graphql query promise not resolved

Hi All i am trying to use graphql api to fetch some country. I am using this API https://studio.apollographql.com/public/countries/home?variant=current and this is playground https://countries.trevorblades.com/

The problem i am facing is that i cannot resolve the Promise. I am using React and fetch method.

my fetchCountries.js file:

import { API_URL } from "./constants";

const COUNTRIES_QUERY = `{
  country(code: "BR") {
    name
    native
    emoji
    currency
    languages {
      code
      name
    }
  }
}`;

const fetchCountries = async () => {
  await fetch(API_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      query: COUNTRIES_QUERY,
    }),
  })
    .then((response) => {
      if (response.status >= 400) {
        throw new Error("Error fetching data");
      } else {
        return response.json();
      }
    })
    .then((data) => data.data);
};

export default fetchCountries;

i am using async, await in the function so that it gets resolved when i call it. Now in my App.js when i call fetchCountries function in console.log i get:

Promise {<pending>}
[[Prototype]]
: 
Promise
[[PromiseState]]
: 
"fulfilled"
[[PromiseResult]]
: 
undefined

App.js:

import "./App.css";
import fetchCountries from "./api/fetchCountries";

const App = () => {
  console.log("CONSOLE LOG API", fetchCountries());

  return <div>App</div>;
};

export default App;

I have also tried to use useEffect hook but got the same result:

import "./App.css";
import fetchCountries from "./api/fetchCountries";
import React, { useEffect, useState } from "react";

const App = () => {
  const [test, setTest] = useState();

  console.log("CONSOLE LOG API", fetchCountries());

  useEffect(() => {
    const getCountries = async () => {
      await fetchCountries();
    };
    setTest(getCountries());
  }, []);
  console.log("USE EFFECT API", test);

  return <div>App</div>;
};

export default App;

You should do it as follows

const fetchCountries = async () => {
  const response = await fetch(API_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      query: COUNTRIES_QUERY,
    }),
  })
    
      if (response.status >= 400) {
        throw new Error("Error fetching data");
      } else {
        return await response.json();
      }
    
};

export default fetchCountries;

Or enclose entire fetch.then... chain inside paranthesis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM