大家好,我正在尝试使用graphql API来获取一些国家。我正在使用这个API https://studio.apollographql.com/public/countries/home?variant=current,这是操场https://countries.trevorblades.com/
我面临的问题是我无法解决承诺。我使用的是React和fetch
方法。
我的fetchCountries.js文件:
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;
我在函数中使用async,wait,这样当我调用它时它就会得到解析。现在在App.js中,当我调用console.log中的fetchCountries函数时,我会得到:
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;
我也尝试过使用useEffect钩子,但得到了相同的结果:
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;
1条答案
按热度按时间uyhoqukh1#
您应该按以下步骤操作
或将整个
fetch.then...
链括在括号内。