Next.js Discord

Discord Forum

Use cache conditional caching?

Answered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
What is the best pattern to conditionally cache function return value with use cache directive and cacheTag?

I have some functions that fetch data from database and have draft argument which when set to true fetches the draft version of the document. This is useful for preview when user is editing something in the admin panel.

I have been thinking about separating my fetch functions into 2 one cached and other not cached, but this leads to too much code duplication.

Do you guys have any ideas?

async function fetchDoc(draft = false) {
  "use cache"

  if (draft) // return live calculated value
  // else return cached value or calculate it if cache miss
}
Answered by Plague
Well if you use next.js built in draftMode API it will bypass all cache, so don't even need to make more than one function, just change how you fetch based on the draft param, that is how I do it.
View full answer

4 Replies

American black bearOP
bump
American black bearOP
bump
Well if you use next.js built in draftMode API it will bypass all cache, so don't even need to make more than one function, just change how you fetch based on the draft param, that is how I do it.
Answer