redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

Add pre-bound cache entry update methods to query hooks

Open markerikson opened this issue 4 weeks ago • 0 comments

One of the things I like about SWR is the ergonomics around mutate.

In the same realm of the discussion in #5073 of helpers around manual cache (mainly optimistic & pessimistic) updates, I think that having easy access to a bound update from a query hook would make a lot of use cases of simpler.

How this works for SWR, example adapted from their docs:

const { data, mutate } = useSWR('/api/user', fetcher) const updateName = async () => { const newName = data.name.toUpperCase() await requestUpdateUsername(newName) mutate({ ...data, name: newName }) }

Hmm. So essentially what we do for cache lifeycles?

  updateCachedData: (isAnyQueryDefinition(endpointDefinition)
    ? (updateRecipe: Recipe<any>) =>
        mwApi.dispatch(
          api.util.updateQueryData(
            endpointName as never,
            originalArgs as never,
            updateRecipe,
          ),
        )
    : undefined) as any,

Seems pretty doable to throw that into the query hooks.

Yeah-- it would be pretty sweet to be able to do:

// Optimistic patch example, within-consumer

const { data: profile, patch: patchProfile } = useGetProfileQuery(userId);
const [updateProfileMutation] = useUpdateProfileMutation();

const updateName = async (name: string) => {
  const patch = patchProfile({ name });
  try {
    await updateProfileMutation(userId, { name });
  catch (error) {
    patch.undo();
  }
}

I think one of the reasons I'm a fan of this approach is that in applications with lots of optimistic / pessimistic updates, it becomes nice for it be super obvious how the updates are occurring from just reading the consumer.

Especially when a variety of strategies are used for updating, and they all start feeling like lots of side effects firing off.

Originally posted by @JacobJaffe in #5149

markerikson avatar Dec 03 '25 22:12 markerikson