Search code examples
reactjsgraphqlreact-hooksswr

SWR with graphql-request how to add variables in swr?


I want to add variables to my swr which fetch using graphql request. this is my code

import { request } from "graphql-request";
import useSWR from "swr";

const fetcher = (query, variables) => request(`https://graphql-pokemon.now.sh`, query, variables);

export default function Example() {
  const variables = { code: 14 };
  const { data, error } = useSWR(
    `query GET_DATA($code: String!) {
                getRegionsByCode(code: $code) {
                  code
                  name
                }
              }`,
    fetcher
  );

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;
  return <pre>{JSON.stringify(data, null, 2)}</pre>;
}

but I dont know how to add variables into swr fetcher as I know useSWR(String, fetcher) string is for query, and fetcher for fetch function, where I can put the variables?


Solution

  • You can use Multiple Arguments, you can use an array as the key parameter for the useSWR react hook.

    import React from "react";
    import { request } from "graphql-request";
    import useSWR from "swr";
    
    const fetcher = (query, variables) => {
      console.log(query, variables);
      return request(`https://graphql-pokemon.now.sh`, query, variables);
    };
    export default function Example() {
      const variables = { code: 14 };
      const { data, error } = useSWR(
        [
          `query GET_DATA($code: String!) {
              getRegionsByCode(code: $code) {
                code
                name
              }
            }`,
          variables,
        ],
        fetcher
      );
    
      if (error) return <div>failed to load</div>;
      if (!data) return <div>loading...</div>;
      return <pre>{JSON.stringify(data, null, 2)}</pre>;
    }
    

    The function fetcher still accepts the same 2 arguments: query and variables.