React-query useQuery,GraphQL + fetch。如何传递变量?
React-query useQuery, GraphQL + fetch. How to pass variables?
我正在尝试从我的 Strapi GraphQl api 获取数据并对它们进行分页。为此,我需要传递变量。我正在使用 react-query 和 fetch api.
在这里我声明我的变量和查询。
const endpoint = "http://localhost:1337/graphql"
let limit: number = 10;
let start: number = 0;
export const QUERY = `
query fetchProducts ($limit: Int!, $start: Int!) {
products(limit: $limit, start: $start) {
title
price
slug
image {
formats
}
}
}
`;
这是我的抓取函数
async function fetchData(endpoint: string, query: string, limit: number, start: number) {
const res = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ query: query }),
});
const json = await res.json();
const {
data: { products },
} = json;
start += 10; //when refetching, it fetches another 10
return products;
}
这是来自 react-query 的 useQuery 钩子
const { data, status, refetch } = useQuery(["blog", limit, start], () => fetchData(endpoint, QUERY, limit, start), {
keepPreviousData: true,
});
我收到错误:
“未提供所需类型“Int!”的变量“$limit”
“未提供所需类型“Int!”的变量“$start”。
所以我没有正确传递变量。我做错了什么?
从 react-query 特定的角度来看,它看起来不错:
- 将所有变量作为查询键的一部分
- 将它们正确传递给 queryFn
我不是 graphQL 专家,但是查看 this example blog post 如何将 graphql 与 fetch
一起使用,您需要在 query
旁边传递 variables
作为您的 fetch
请求的 body
。
类似于:
body: JSON.stringify({
query: query,
variables: { limit, start }
}),
我认为如果你使用像 graphql-request
这样的轻量级抽象,这会变得更容易一些,这也是 react-query example 使用的。
我正在尝试从我的 Strapi GraphQl api 获取数据并对它们进行分页。为此,我需要传递变量。我正在使用 react-query 和 fetch api.
在这里我声明我的变量和查询。
const endpoint = "http://localhost:1337/graphql"
let limit: number = 10;
let start: number = 0;
export const QUERY = `
query fetchProducts ($limit: Int!, $start: Int!) {
products(limit: $limit, start: $start) {
title
price
slug
image {
formats
}
}
}
`;
这是我的抓取函数
async function fetchData(endpoint: string, query: string, limit: number, start: number) {
const res = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ query: query }),
});
const json = await res.json();
const {
data: { products },
} = json;
start += 10; //when refetching, it fetches another 10
return products;
}
这是来自 react-query 的 useQuery 钩子
const { data, status, refetch } = useQuery(["blog", limit, start], () => fetchData(endpoint, QUERY, limit, start), {
keepPreviousData: true,
});
我收到错误:
“未提供所需类型“Int!”的变量“$limit”
“未提供所需类型“Int!”的变量“$start”。
所以我没有正确传递变量。我做错了什么?
从 react-query 特定的角度来看,它看起来不错:
- 将所有变量作为查询键的一部分
- 将它们正确传递给 queryFn
我不是 graphQL 专家,但是查看 this example blog post 如何将 graphql 与 fetch
一起使用,您需要在 query
旁边传递 variables
作为您的 fetch
请求的 body
。
类似于:
body: JSON.stringify({
query: query,
variables: { limit, start }
}),
我认为如果你使用像 graphql-request
这样的轻量级抽象,这会变得更容易一些,这也是 react-query example 使用的。