So you did now learn
how you can cache data from your own data source.
However, now that we added this caching,
we'll face a problem even during development.
If I now add a new fourth message, it doesn't appear here.
A problem we previously only faced in production
due to that full route cache.
Now, since we set up this cache here,
and hence we got this data cache, we got the same problem,
if you want to call it like this, during development.
But it's not actually a problem.
Instead, it's the behavior NextJS has out of the box,
it caches aggressively.
What we have to do to see our data again,
is we have to tell NextJS
that the data that's cached here did change.
And how can we tell NextJS?
Well, there are essentially two main ways.
In the place where we create that new data
we can call that revalidatePath function again,
and we saw that function before already.
And I can, for example,
revalidate the data on /messages.
With that any cached data used on this page
will be thrown away and will be re-fetched
whenever this function here was called.
So right after adding a new message,
I'm calling this function to tell NextJS
that any data and the full route cache
of the /messages page should be thrown away
and the data should be re-fetched
and the page should be re-rendered.
Therefore, with this added,
I still don't see the message if I reload,
but now for every new message we add,
the cache will be cleared
and hence, any new messages now will show up here.
As you can tell.
So that's one way.
Now, an alternative to calling revalidatePath
and revalidate the data that's attached
to a specific page is to instead call revalidateTag
and add a tag to the cached data.
And you can add a tag to cached data
when using unstable_cache,
which I renamed to nextCache here in my case,
by passing a third argument
to this unstable_cache function.
And that third argument is a configuration object,
which allows you to set up two different settings.
With revalidate, you could set up a time period,
in seconds again, after which the cache
would always be re-validate.
So that would be another way of re-setting it
or re-fetching. But here I'm looking for the tags setting.
And this then takes an array of tags,
which are totally up to you.
So you can add as many tags as you want
and any tag values of your choice.
That will then add those tags to this cached data.
And if you then call revalidateTag with one of these tags,
that data will be thrown away
and any place in your NextJS application,
any page layout or component that fetches data
from that data source with that tag
will be re-executed and the respective page
and component will be re-rendered.
So with this setup,
if I now add a new message here like this,
that message also shows up here
because we're using revalidateTag.
And that's how you can invalidate the cache data
when managing the cache on your own.