So how can we fix this problem
of NextJS caching too aggressively?
Well, we need to tell NextJS to throw away its cache
or parts of its cache whenever we add a new meal.
And of course, this is such a common requirement
that there's a built-in method for that,
a built-in function provided by NextJS,
a function which I wanna execute in my server action
right after saving a meal before I redirect.
And that function is called revalidatePath.
This function tells NextJS
to revalidate the cache
that belongs to a certain route path.
So for example, if I know that I want
to visit the meals page
and that the meals page depends on data that changed now,
I can tell NextJS to revalidate the /meals path.
And with that, that path would be revalidated.
Now what's important is that,
by default, only that path will be revalidated,
no nested paths.
So if I had some nested path there in my meals folder,
that also depends on all the meals data,
I would have to revalidate that separately.
Alternatively, you can pass a second argument
to revalidate path and set this to layout.
The default is page, which means that simply this one page
for this one path will be revalidated.
If you set it to layout,
it's the layout that will be revalidated,
which as you learned, also wraps nested pages,
and therefore, with this,
all nested pages would be revalidated as well.
And revalidate simply means
that NextJS throws away the cache that is associated
with those pages.
So, for example, the cached pages themselves.
Now here, I don't care about any nested pages
because the dynamic page here isn't pre-generated anyways
in our current setup
and the share page doesn't depend on the meals data.
So I'm fine with just revalidating /meals.
If you would want to revalidate all the pages
of your entire website, you could, by the way, do that
by targeting slash and then setting the mode to layout.
But here, I'm fine with just revalidating the meals path.
Well, and with that done, if we now run npm run build again
to build all those pages again,
they will still be pre-generated and cached,
but now that cache should be revalidated
and partially cleared once we added a new meal.
So if I now run npm start again
to start that development server,
and I then add another new meal,
like this, picking the same image as always,
if I submit that,
it takes a bit longer here, which is a good sign
because it's taking longer
because it loaded all those meals again.
And here we are, now the image is missing,
we'll take care of that in just a second.
But the meal is there and that's of course a good sign.
In addition, we got these Fetching meals logs back here,
which also proves that this is now working as intended.