Next JS 13 caching in app directory not working
Unanswered
Gyrfalcon posted this in #help-forum
GyrfalconOP
I'm using
I've this route at
cache function in server only component but whenever I'm changing data on the BE I'm always getting the updated data and not from the cache. Why so? I've this route at
app/page.tsx:import { getUsers } from "@/utils/getUser";
export const revalidate = 5;
export default async function Home() {
const users: any[] = await getUsers();
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
{users.map((user) => (
<h1 key={user.id}>{user.name}</h1>
))}
</main>
);
}utils/getUser.tsimport axios from "axios";
import { cache } from "react";
export const getUsers = cache(async () => {
const users = (
await axios.get("https://64baaf385e0670a501d6887f.mockapi.io/users")
).data;
console.log({ users });
return users;
});14 Replies
@Gyrfalcon I'm using `cache` function in server only component but whenever I'm changing data on the BE I'm always getting the updated data and not from the cache. Why so?
I've this route at `app/page.tsx`:
tsx
import { getUsers } from "@/utils/getUser";
export const revalidate = 5;
export default async function Home() {
const users: any[] = await getUsers();
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
{users.map((user) => (
<h1 key={user.id}>{user.name}</h1>
))}
</main>
);
}
`utils/getUser.ts`
ts
import axios from "axios";
import { cache } from "react";
export const getUsers = cache(async () => {
const users = (
await axios.get("https://64baaf385e0670a501d6887f.mockapi.io/users")
).data;
console.log({ users });
return users;
});
you are caching it for 5 seconds only – so by the time you completed updating the data in the db, the 5 sec window has already ended and the page will be recomputed again
@joulev you are caching it for 5 seconds only – so by the time you completed updating the data in the db, the 5 sec window has already ended and the page will be recomputed again
GyrfalconOP
@joulev Even if I do it for an hour it'll still be getting on each call
@Gyrfalcon <@484037068239142956> Even if I do it for an hour it'll still be getting on each call
an hour as in
export const revalidate = 3600?GyrfalconOP
Yes
dev mode or prod mode?
GyrfalconOP
Dev
in dev mode then everything is dynamic
in prod mode it will work like you expect it to
GyrfalconOP
@joulev But if I use
fetch in dev mode, then caching is working fineI've a use case where I can't use
fetchuhm, no that shouldn't happen. basically the cache() here only handles deduplication, not cross-render caching
wait i had a long explanation about this yesterday, lemme grab the link
cache() is not a one-on-one replacement of fetch() though; cache() doesn't have tags and granular cache control that fetch() has. that is something you need to note