swr icon indicating copy to clipboard operation
swr copied to clipboard

Revalidate useSWR by considering only the first argument when using multiple arguments.

Open justAnArthur opened this issue 1 year ago • 1 comments

Bug report

Description / Observed Behavior

I'm incorporating the table state, such as filters and sorting, into the body of a fetch request. Previously, I utilized a custom use hook that invoked an API call whenever path or body changed.

Upon transitioning to useSWR, I now need to pass the body as the second argument to ensure unique data retrieval for different body configurations:

useSWR([subPath, body && JSON.stringify(body)],  ...)

However, as highlighted in 363, the revalidation process requires passing the entire array of multiple arguments: mutate(["/api/users", 1]);, which seems somewhat redundant.

Expected Behavior

Mutate data by first key - url/subPath. As: mutate("/api/users");

Repro Steps / Code Example

-

Additional Context

I believe there's no necessity for a full revalidation across all arguments, as most users, like myself, primarily utilize multiple arguments solely for passing the body.

justAnArthur avatar Dec 11 '23 09:12 justAnArthur

I am not sure if this helps, but you can revalidate based on just one item of the array (or part of a string) like this:

https://swr.vercel.app/docs/mutation#mutate-multiple-items

From the docs:

useSWR(['item', 123], ...)
useSWR(['item', 124], ...)
useSWR(['item', 125], ...)
 
mutate(
  key => Array.isArray(key) && key[0] === 'item',
  undefined,
  { revalidate: false }
)

teooliver avatar Mar 15 '24 18:03 teooliver