Search code examples
reactjsreact-hooksgraphqlnext.jsswr

useSWR with graphql-request keeps sending requests infinitely after arguments are passed


Here I am creating a custom hook for getting list of bookings with arguments, search, which is the status of the booking and is by default 'NEW' and it can be reused anywhere with different search value and get the status bookings.

The problem is that request is successful and its getting the result according to the argument passed.

But on Network calls it keeps sending the request infinitely to the server, like 4 requests/sec

Custom Hook for getting Bookings

import { getBookingList } from "@graphql/bookings/queries";
import { swrFetcher } from "../fetcher";
import useSWR from "swr";

function useBooking(search="NEW") {
    const { data, error } = useSWR([getBookingList, {search}], swrFetcher);
    return { data: data && data?.bookingList, error };
}

export default useBooking;

This is the graphql query that is taking the arguments and being executed.

GraphqQL Query for getting booking list with input arguments.

import { gql } from "graphql-request";

export const getBookingList = gql`
    query getBookingList($search: String) {
        bookingList(search: $search) {
            id
            date
            pickupLoc {
                coordinates
            }
            dropoffLoc {
                coordinates
            }
            time
            pickup
            dropoff
            journey
            price
            name
            status
            driver {
                id
                referenceId
                user {
                    username
                }
            }
            driverNotes
            customerNotes
            customer {
                phone
            }
            paymentType
            vehicleType {
                name
            }
        }
    }
`;

This is my swrFetcher which is used to fetch the data from graphql with SWR.

import { GraphQLClient } from "graphql-request";

const graphqlFetcher = new GraphQLClient(`${process.env.NEXT_PUBLIC_GRAPHQL_API}`);

export const swrFetcher = (query, variables) => graphqlFetcher.request(query, variables);

I followed this Arguments in SWR and the answer here, but nothing helped.


Solution

  • My mistake, i was doing it wrong. After looking onto the Multiple Arguments section of the here it was clearly mentioned about this issue. Just needed to change my custom hook to this:

    const { data, error } = useSWR([getBookingList, search], (url, value) => swrFetcher(url, { search: value }));
    

    and everything worked after that.