我正在为星球大战API ( GraphQL https://swapi.dev/api/)开发阿波罗API。我希望使用从第一个API调用中获得的数据进行第二个API调用,以便在第二个API调用中获得家乡的name属性。我已经成功地进行了第一个API调用,现在我不得不使用来自第一个API调用的数据进行第二个api调用。
第一个API调用的代码如下所示:(index.js)
const restLink = new RestLink({ uri: "https://swapi.dev/api/" });
const client = new ApolloClient({
link: restLink,
cache: new InMemoryCache(),
});
第一个API调用:
import { useQuery, gql } from "@apollo/client";
const GET_CHARACTERS = gql`
query {
people @rest(path: "people/") {
results {
name
height
mass
gender
homeworld
}
}
}
`;
const {
error: peopleError,
data: peopleData,
loading: peopleLoading,
} = useQuery(GET_CHARACTERS);
return {
peopleError,
peopleData,
peopleLoading,
};
第一个API调用被发送到:https://swapi.dev/api/people/,它用下面显示的数据返回对象(我只显示了第一个对象):
{
name: "Luke Skywalker",
height: 172,
age: 77,
gender: "male",
hometown: "https://swapi.dev/api/planets/1/"
}
在得到它之后,我必须再次调用API (https://swapi.dev/api/planets/1/),这个API是由 will 对象键带回的,这样当我显示数据时,它将在API中显示家乡的name属性。家乡API的数据如下所示:
{
"name": "Tatooine",
"rotation_period": "23",
"orbital_period": "304",
"diameter": "10465",
"climate": "arid",
"gravity": "1 standard",
"terrain": "desert",
"surface_water": "1",
"population": "200000",
}
发布于 2022-04-15 00:40:34
这就是所谓的“依赖查询”。你可以在这里读到你的确切案例:https://www.apollographql.com/blog/apollo-client/using-apollo-link-to-handle-dependent-queries/
主要是在查询配置中使用skip选项,如下所示:
const { data: profileData } = useQuery(PROFILE_INFO)
const planetId = profileData?.planet?.id
const { data: planetData } = useQuery(PLANET,
skip: !planetId, // Only run this query if the first query has completed
variables: { planetId }
)发布于 2022-04-16 04:24:39
您所面临的挑战不是如标题所暗示的“如何调用依赖的查询”,而是“如何调用动态数量的查询”。
React查询将其称为,并提供了一个useQueries (注意复数)钩子来使用它。阿波罗出现在面前。在同样的问题上,GitHub用户拥有可以像这样使用的posted their implementation of a useQueries hook for Apollo:
const graphResults = useQueries(
graphs.map(graph => ({
query: GET_INSIGHT,
variables: { ...graph, interval, from, to },
/* specific useQuery options */
})),
{ /* general useQuery options */ },
);在我看来,更合适的解决方案是通过直接使用ApolloClient.query调用阿波罗客户端,为任何需要N个调用的查询编写自己的钩子。下面是我的另一个模式:
function useRates(currencies) {
const client = useApolloClient();
const [results, setResults] = useState({});
useEffect(() => {
let isStale = false;
setResults({});
for (let currency of currencies) {
const rates = client.query({
query: ratesQuery,
variables: { currency }
});
rates.then((result) => {
if (!isStale)
setResults((results) => ({ ...results, [currency]: result.data.rates }));
});
}
return () => (isStale = true);
}, [client, currencies.join(",")]);
return results;
}演示:https://codesandbox.io/s/get-started-coinbase-client-forked-lfwtig?file=%2Fsrc%2Findex.js%3A744-1316
https://stackoverflow.com/questions/71878841
复制相似问题