Skip to content

Mutate multiple call results #264

@kelleyvanevert

Description

@kelleyvanevert

I'd like to be able to mutate the cached results for a variable number of call results. Essentially, what I'm after is a mutate function not with the current signature:

mutate(
  key,
  data,
  shouldRevalidate?
): void

..but rather with a signature something like this:

mutateMany(
  select: (key) => boolean,
  update: (result: R) => R
): void

or this:

type updater = (result: R) => R
mutateMany(
  selectivelyUpdate: (key) => void | updater
): void

In PR #245 (Improve mutate function) I found a clever trick (the "bound mutator") to relatively easy work around the current non-existence of this feature. I made a little userland proof-of-concept out of the idea, which looks something like this:

import useSWR, { mutate as swrMutate } from "swr";

const BOUND_MUTATORS: Array<{ key, boundMutator }> = [];

export function useWrappedSWR(key, ...) {
  const swr = useSWR(key, ...);

  useIsomorphicLayoutEffect(() => {
    if (key) {
      const entry = {
        key,
        boundMutator(update: (result: any) => any) {
          if (swr.data) {
            swrMutate(key, update(swr.data));
          }
        }
      };

      BOUND_MUTATORS.push(entry);

      return () => {
        const i = BOUND_MUTATORS.indexOf(entry);
        if (i >= 0) {
          BOUND_MUTATORS.splice(i, 1);
        }
      };
    }
  }, [key]);

  return swr;
}

export function mutateMany(selectivelyUpdate: (key: any) => void | ((result: any) => any)) {
  BOUND_MUTATORS.forEach(({ key, boundMutator }) => {
    const update = selectivelyUpdate(key);
    if (update) {
      boundMutator(update);
    }
  });
}

👉 Is this kind of feature something you are looking into, or willing to think about/support?

I'd be very very happy, am looking forward to using this library but currently rely on this kind of (self-written) cache updating logic in a project of mine with a relatively large codebase :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussionDiscussion around current or proposed behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions