You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You can now pass a filter function to the global mutate API to match any keys and mutate them together:
import{mutate}from'swr'// Or from the hook if you customized the cache provider:// { mutate } = useSWRConfig()mutate(key=>typeofkey==='string'&&key.startsWith('/api/item?id='),data=>update(data),true)
This action will match all keys starting with '/api/item?id=', and replace their data with update, then re-fetch after the mutation. The signature is the same as the current mutate API:
The only difference is if you pass a function instead of a specific key, SWR will use it to match and mutate all the data in the cache. It will be convenient to use this to batch updates, or mutate keys by pattern.
Worth noting that it works with any key types, too:
The mutation above will match all 3 keys and set the values to undefined (clear them), and skip the revalidation at the end. So another technique is to clear everything with this (e.g. when logging out):
mutate(()=>true,undefined,false)
More use cases and discussions can be found in the original RFC: #1946.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Highlights & Breakings
Mutate Multiple Keys (#1946, #1989)
You can now pass a filter function to the global
mutate
API to match any keys and mutate them together:This action will match all keys starting with
'/api/item?id='
, and replace their data withupdate
, then re-fetch after the mutation. The signature is the same as the current mutate API:The only difference is if you pass a function instead of a specific key, SWR will use it to match and mutate all the data in the cache. It will be convenient to use this to batch updates, or mutate keys by pattern.
Worth noting that it works with any key types, too:
The mutation above will match all 3 keys and set the values to undefined (clear them), and skip the revalidation at the end. So another technique is to clear everything with this (e.g. when logging out):
More use cases and discussions can be found in the original RFC: #1946.
What's Changed
Full Changelog: 2.0.0-beta.4...2.0.0-beta.5
This discussion was created from the release 2.0.0-beta.5.
Beta Was this translation helpful? Give feedback.
All reactions