Update infinite query data

React query does not expose any utils for easy management of cached inifinite query data. If a mutation changes an item, we have to manually get the cached data, find the item and manually update it. The data structure of an infinite query is based on an object of pages and pageParams.

export interface InfiniteData<TData> {
pages: TData[];
pageParams: unknown[];
}

pages consists of a list of entities coming from the server. pageParams is a list of cursors, used for pagination. The most common format of a data entity within a page is:

interface MessagesInfiniteQueryResponse {
data: MessageResponse[];
nextCursor?: string;
}

As you can see, a complete infinite query dataset can be somewhat complex, and equally hard to maintain when the number of infinite queries increases, e.g. lazy loaded data in the application. In order to keep the code DRY, a set of utility functions for easy cache management has been implemented.

updateInfiniteQueryItem()#

updateInfiniteQueryItem is a simple utility function located in the src/utils/api/ folder, used for easy updates of cached infinite query date. The function takes two arguments; id and options.

updateInfiniteQueryItem does a shallow merge of the existing item and the item passed with options. Nested object properties will not be merged.

Function arguments#

id

The id of the item to be updated. Must be a number.

options

An object containing the infinite query pages and the data to be updated.

interface Props<T> {
pages: { data: RequiredProps<T>[] }[];
item: RequiredProps<T>;
}

Required properties

These propterties must be provided by the item passed with options.

type RequiredProps<T> = T & {
id: number,
};

Usage#

// Update message with response from server
onSuccess: (item: MessageResponse) => {
queryClient.setQueriesData<InfiniteData<MessagesInfiniteQueryResponse> | undefined>(queryKey, previousData => {
if (!previousData) return undefined;
// Update cache with response from server
const pages = updateInfiniteQueryItem<MessageResponse>(id, { pages: previousData.pages, item });
return { ...previousData, pages };
});
}
me

Previous

Push Notifications

Next

Upgrading React Native

me