Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
787 B
1
Indexable
Never
  const { cache } = useSWRConfig();

  function useMatchMutate() {
    const { cache, mutate } = useSWRConfig();
    return (matcher: any, ...args: any) => {
      if (!(cache instanceof Map)) {
        throw new Error("matchMutate requires the cache provider to be a Map instance");
      }

      const keys = [];

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      for (const key of cache.keys()) {
        if (matcher.test(key)) {
          keys.push(key);
        }
      }

      console.log("keys", keys);

      const mutations = keys.map((key) => mutate(key, ...args));
      return Promise.all(mutations);
    };
  }

  const matchMutate = useMatchMutate();

<button onClick={() => matchMutate(/service-category/)}>Mutate All</button>