Skip to content

useSWRInfinite - Mutate multiple items #4104

@MuellerConstantin

Description

@MuellerConstantin

Bug report

Description / Observed Behavior

According to the documentation it is possible to mutate multiple items. I use that because some of my requests contain dynamic query parameter for pagination control, and in case of a newly added item I have to refresh the whole collection, hence all request independent of the actual page index. Because of that, I cannot simply pass a string as key, instead I use the matcher argument.

This works fine for useSWR with global mutation:

mutate((key) => /^\/boards.*$/.test(key), null);

In addition I have a page with infinite loading that is using useSWRInfinite. Again I have to revalidate all pages of the collection. The documentation suggests to use mutate(unstable_serialize(getKey)) (I know it's unstable). This works well within the same component in which the useSWRInfinite call occurs. But now I have to revalidate across all pages globally. Sadly, unstable_serialize doesn't work with a matcher function or regex, only strings are supported.

I found out, that infinite key are prefixed with $inf$. So my idea was to skip unstable_serialize and use something like the following:

mutate((key) => /^\$inf\$\/boards.*$/.test(key), null);

Problem:

The infinite keys (Keys prefixed with $inf$) never seem to be handed over to the matcher function. The "normal" keys are handed over, but not the infinite keys. But the keys are definitely present in cache, I checked it and my workaround is based on it.

Expected Behavior

Maybe I missed something but I would expect, that the infinite keys would be handed over too, so the matcher function can deal with them. This way I wouldn't have to build a workaround.

Repro Steps / Code Example

// Component A

const getKey = (pageIndex, previousPageData) => {
  if (previousPageData && !previousPageData.content.length) return null;
  return `/boards?page=${pageIndex}&perPage=25`;
};

const {
  data,
  error,
  size,
  setSize,
} = useSWRInfinite(getKey, (url) => api.get(url).then((res) => res.data));
// Component B
const { mutate } = useSWRConfig();

mutate((key) => {
  console.log(key); // Infinite keys never occur
  return /^\$inf\$\/boards.*$/.test(key);
}, null);

Additional Context

SWR Version: 2.3.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions