Search code examples
reactjsgraphqlfetch-apireact-query

React-query useQuery, GraphQL + fetch. How to pass variables?


I'm trying to fetch data from my Strapi GraphQl api and paginate them. For that I need to pass down variables. I'm using react-query and fetch api.

Here I declare my variables and query.

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
    }
  }
}
`;

Here is my fetching function

  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;
}

And here is useQuery hook from react-query

const { data, status, refetch } = useQuery(["blog", limit, start], () => fetchData(endpoint, QUERY, limit, start), {
    keepPreviousData: true,
});

I get errors:

"Variable "$limit" of required type "Int!" was not provided

"Variable "$start" of required type "Int!" was not provided.

So I'm not passing variables correctly. What am I doing wrong?


Solution

  • From a react-query specific perspective, it looks good:

    • having all variables as part of the query key
    • passing them correctly to the queryFn

    I'm no graphQL expert, but looking at this example blog post on how to use graphql with fetch, you need to pass variables next to the query as the body of your fetch request.

    Something like:

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

    I think this becomes a bit easier if you use a lightweigt abstraction, like graphql-request, which is also what the react-query example uses.