Skip to content

1.2.2

Compare
Choose a tag to compare
@shuding shuding released this 18 Feb 19:11
f24c621

Highlights of This Release

populateCache Option Now Supports Function

We added better Optimistic UI support in v1.2.0. However, what if your API is only returning a subset of the data (such as the mutated part), that can be populated into the cache? Usually, an extra revalidation after that mutation is needed. But now you can also use a function as populateCache to transform the mutate result into the full data:

await mutate(addTodo(newTodo), {
  optimisticData: [...data, newTodo],
  rollbackOnError: true,
  populateCache: (addedTodo, currentData) => {
    // `addedTodo` is what the API returns. It's not
    // returning a list of all current todos but only
    // the new added one.
    // In this case, we can transform the mutate result
    // together with current data, into the new data
    // that can be updated.
    return [...currentData, addedTodo];
  },
  // Since the API already gives us the updated information,
  // we don't need to revalidate here.
  revalidate: false,
});

The new definition:

populateCache?: boolean | ((mutationResult: any, currentData: Data) => Data)

Here is a demo for it: https://codesandbox.io/s/swr-basic-forked-hi9svh

Bug Fixes

What's Changed

  • refactor: revalidateIfStale has an effect on updates, not only mounting by @koba04 in #1837
  • fix: reset stale unmountedRef in suspense by @promer94 in #1843
  • test: add a test for the behavior of revalidateOnMount when the key has been changed by @koba04 in #1847
  • feat: Support populateCache as a function by @shuding in #1818

Full Changelog: 1.2.1...1.2.2