Updating GraphQL cache after each fired query

Updating GraphQL cache after each fired query


0

I am currently trying to fire a GraphQL query several times on scroll and after each time store the result in local cache without overwriting the previous one. In React I could achieve this easily using local state and setting it to [...oldData, ...newData]. However I have no luck doing this via GraphQL.

I’ve tried creating a wrapper around my query but that only results in my query constantly firing.

const useLazyHotelQuery = (
  guestId?: number,
  destination?: string,
  checkInDate?: number
) => {
  const [getHotelData, { hotelData, isLoading, hotelClient }] = useLazyQuery<
    HotelData,
    HotelVars
  >(HOTEL_SEARCH, {
    variables: {
      guestId,
      destination,
      checkInDate,
      roomLimit: 100,
    },
    fetchPolicy: 'hotel-cache-and-network',
  });

  const saveDataToHotelCache = (newHotelData: HotelData, hotelVars?: HotelVars) => {
    hotelClient.writeQuery({
      query: HOTEL_SEARCH,
      variables: hotelVars,
      data: newHotelData,
    });
  };

  const mainHotelFn = (hotelVars?: HotelVars) => {
    getHotelData({
      variables: hotelVars,
    }).then(({ data: newHotelData }) => {
      if (newHotelData) {
        saveDataToHotelCache(newHotelData, hotelVars);
      }
    });
  };

  return [mainHotelFn, { hotelData, isLoading, hotelClient }] as const;
};

and in React, I call it like const [mainHotelFn, { hotelData, isLoading }] = useLazyHotelQuery(id);

What is the easiest way to update the apollo cache with the new data after each query? The Apollo documentation is quite confusing and I can’t figure it out.


Load 4 more related questions


Show fewer related questions

0



Leave a Reply

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