github vercel/swr 2.0.0-beta.5

latest releases: v2.2.6-beta.2, v2.2.6-beta.1, v2.2.6-beta.0...
pre-release22 months ago

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:

import { mutate } from 'swr'
// Or from the hook if you customized the cache provider:
// { mutate } = useSWRConfig()

mutate(
  key => typeof key === '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:

mutate(
  '/api/item?id=123',
  data => update(data),
  true
)

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:

useSWR(['item', 123], ...)
useSWR(['item', 124], ...)
useSWR(['item', 125], ...)

mutate(
  key => Array.isArray(key) && key[0] === 'item',
  undefined,
  false
)

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.

What's Changed

  • feat: Mutate multiple keys by @huozhi in #1989
  • fix: Avoid preloading the resource multiple times by @shuding in #2036
  • fix: isLoading and isValidating should always respect cache value by @promer94 in #2048
  • chore: Fix TS type generation by @huozhi in #2038

Full Changelog: 2.0.0-beta.4...2.0.0-beta.5

Don't miss a new swr release

NewReleases is sending notifications on new releases.