Next.js Discord

Discord Forum

Cache invalidation

Answered
Horned oak gall posted this in #help-forum
Open in Discord
Horned oak gallOP
Somewhat generic title, but fits pretty well. Assuming I do use unstable_cache (or built-in caching with fetch), how would I invalidate this cache properly, especially for cases where another user is mutating data in my database? I'm currently using a RefreshOnFocus component:

"use client";

export function RefreshOnFocus() {
  const { refresh } = useRouter();

  useEffect(() => {
    const onFocus = () => {
      refresh();
    };
    window.addEventListener("focus", onFocus);
    return () => {
      window.removeEventListener("focus", onFocus);
    };
  }, []);

  return null;
}


But there's still some issues:

1. it's a client component, hence has no access to revalidateTag or revalidatePath
2. even then the issue would persist if the user stays in the window.

Example:

User A opens the user list (that comes from the db and is cached), user B deletes some users - how user A ever gets to know that?
Answered by Ray
if you delete the data with server action, you can use revaldateTag or revalidatePath after the database operation
View full answer

5 Replies