Next.js Discord

Discord Forum

revalidateTag: Bust cache for a single entry?

Answered
Australian Freshwater Crocodile posted this in #help-forum
Open in Discord
Australian Freshwater CrocodileOP
I have a cache set up like

const getUser = unstableCache(
  (userId) => getUserFromDb(userId), 
  ["user"]
);


how can i bust the cache for ONE user? revalidateTag("user") either busts nothing, or busts the cache for all users.
Answered by joulev
const getUser = (userId) =>
  unstableCache(
    (userId) => getUserFromDb(userId), 
    [],
    { tags: [`user:${userId}`] },
  )(userId);

revalidateTag(`user:${userId}`);
View full answer

15 Replies

@Australian Freshwater Crocodile I have a cache set up like tsx const getUser = unstableCache( (userId) => getUserFromDb(userId), ["user"] ); how can i bust the cache for ONE user? `revalidateTag("user")` either busts nothing, or busts the cache for all users.
const getUser = (userId) =>
  unstableCache(
    (userId) => getUserFromDb(userId), 
    [],
    { tags: [`user:${userId}`] },
  )(userId);

revalidateTag(`user:${userId}`);
Answer
note that in your case, you are putting the user inside the key array, which is not the tag array, so revalidateTag("user") doesn't work.
Australian Freshwater CrocodileOP
I see, thanks!
I thought this was done by Next? From the docs:

keyParts: This is an array that identifies the cached key. It must contain globally unique values that together identify the key of the data being cached. The cache key also includes the arguments passed to the function.
so isn't adding these keys redudant?
@Australian Freshwater Crocodile so isn't adding these keys redudant?
yeah for me the keypart array is not needed most of the times, you don't really need to think about it
just think of it this way: if any strings inside the keypart array changes, then the cache is invalidated (basically)
iirc the function's string form (Function.toString() is an implicit key in that keypart array
to tag a query for revalidateTag, you need to use the tag array not the keypart array
Australian Freshwater CrocodileOP
sounds a bit funky... Most of the times i want to revalidate based on the inputs of the function. your construction probably orks (still testing it),.... but its heck a verbose...

unstable_cache query keys should have an api like react-query (i.e.: string[] | args => string[])
Well… it’s unstable for a reason. The API can change when it becomes stable
For now, this is what we are stuck with and have to use
Australian Freshwater CrocodileOP
Got it. Let’s see when it becomes stable 😂
Thanks for the help
It worked