Issue with Passing Variables in useSWR with graphql-request

Issue with Passing Variables in useSWR with graphql-request


0

I’m facing an issue while using the useSWR hook from the SWR library along with the "graphql-request" library to fetch data from my GraphQL server. The problem seems related to passing variables to the query using the useSWR hook.

I have a GraphQL query defined as follows:

export const GetArticleById = /* GraphQL */ `
  query GetArticleById($where: ArticleWhere!) {
    articles(where: $where) {
      description
      name
      stores {
        store_name
        address
        articlesConnection {
          edges {
            current_price
          }
        }
      }
    }
  }
`;

And I’m using the useSWR hook as follows:

...
const fetcher = (query, variables) => graphqlClient.request(query, variables);
<SWRConfig value={{ fetcher }}>
  //wrapping my component
<SWRConfig>
...

const { data, error, isLoading } = useSWR([
    GetArticleById,
    {
      where: {
        id: "article123",
      },
    },
]);
console.log({data}, {error})// Data here is undefined and I receive a "Cannot read properties of undefined (reading 'filter')" error.

The funny thing is that if I call that query without any variables/params, I actually get the data back—just not the one I want by ID, but every article from the graph:

const { data, error, isLoading } = useSWR(
    GetArticleById
);
console.log(data)// data here is [{article 1}, {article 2} etc]

I suspect that there might be an issue with how I’m passing the variables to the useSWR hook. I’ve checked that the variable names and types match between the query and the useSWR call.

If anyone has experience using the swr library along with graphql-request and can provide insights into the correct way to pass variables to the useSWR hook, I’d greatly appreciate your help.

Thank you in advance for any assistance!

Share
Improve this question


Load 6 more related questions


Show fewer related questions

0

Reset to default



Leave a Reply

Your email address will not be published. Required fields are marked *