-
Let's suppose the user made an action that changed a big part of the page. How do I refresh everything, without calling "revalidate" or "mutate" on every single hook? I thought of simulating a focus on the page, but is there a cleaner way of doing this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
With the latest cache API you can do this: https://swr.vercel.app/docs/advanced/cache#mutate-multiple-keys. |
Beta Was this translation helpful? Give feedback.
-
I wanted to stick with the default cache (the multiple keys section seemed too much and also didn't have the notion of active queries), so I went with my own hook: // hooks/use-query.js
import { useEffect } from "react";
import useSWR from "swr";
const activeQueries = [];
export async function revalidateLiveQueries() {
let allRevalidations = activeQueries.map((mutate) => mutate());
await Promise.all(allRevalidations);
}
export default function useQuery(key, options) {
let { data, error, mutate } = useSWR(key, options);
useEffect(() => {
activeQueries.push(mutate);
return () => {
let i = activeQueries.indexOf(mutate);
if (i > -1) {
activeQueries.splice(i, 1);
}
};
}, [mutate]);
return { data, error };
} I have a // hooks/use-mutation.js
import { request } from "@/lib/data";
import { revalidateLiveQueries } from "./use-query";
export default function useMutation(mutation) {
return [
async function (variables = {}) {
let res = await request(mutation, variables);
await revalidateLiveQueries();
return res;
},
];
} and so far it's working great! |
Beta Was this translation helpful? Give feedback.
With the latest cache API you can do this: https://swr.vercel.app/docs/advanced/cache#mutate-multiple-keys.