-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Description
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
): voidor this:
type updater = (result: R) => R
mutateMany(
selectivelyUpdate: (key) => void | updater
): voidIn 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 :)