【问题标题】:React-query useQuery, GraphQL + fetch. How to pass variables?反应查询 useQuery,GraphQL + fetch。如何传递变量?
【发布时间】:2021-08-29 16:45:07
【问题描述】:

我正在尝试从我的 Strapi GraphQl api 获取数据并将它们分页。为此,我需要传递变量。我正在使用 react-queryfetch 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”。

所以我没有正确传递变量。我做错了什么?

【问题讨论】:

    标签: reactjs graphql fetch fetch-api react-query


    【解决方案1】:

    从 react-query 特定的角度来看,它看起来不错:

    • 将所有变量作为查询键的一部分
    • 将它们正确传递给 queryFn

    我不是 graphQL 专家,但在查看 this example blog post 如何将 graphql 与 fetch 一起使用时,您需要将 variables 传递到 query 旁边,作为您的 body 请求的 body .

    类似:

    body: JSON.stringify({
      query: query,
      variables: { limit, start }
    }),
    

    我认为如果您使用轻量级抽象,这会变得更容易一些,例如 graphql-request,这也是 react-query example 使用的。

    【讨论】:

    • 谢谢,向正文添加变量解决了这个问题! :)
    猜你喜欢
    • 2017-05-15
    • 2017-10-30
    • 2022-01-24
    • 1970-01-01
    • 2019-10-16
    • 2019-01-26
    • 2022-11-30
    • 2020-11-30
    • 2020-07-09
    相关资源
    最近更新 更多