So having that request deduplication is nice.
It would also be nice to have
that data cache functionality though,
which we also get out of the box
when using the fetch function.
Now for our own functions and our own data sources,
we can enable caching by importing another function,
this time, a function that must be imported from next/cache.
And here it's the unstable_cache function.
So another function called cache,
though just as with the unstable_no_store function,
at the point of time where you are viewing this,
this might no longer be marked as unstable
and it might therefore just be called cache.
And then to avoid name clashes,
you might want to assign an alias here.
Now, at the point of time where I'm recording this,
it's still is marked as unstable.
I'll still assign that alias here though,
but we can still use it
and we use it in a kind of similar way
as we used this cache function provided by React.
You wrap this unstable_cache function,
or in my case since I renamed it nextCache,
you wrap that around the function that should be cached,
which can be a function that's already wrapped by cache,
that's fine.
So now I got multiple layers of wrapping going on here,
but the inner cache wrapping here
is for a request deduplication.
The outer wrapping,
the nextCache function here,
is for making this data that's returned by that function
cacheable by NextJS in its data cache.
And with nextCache wrapped around this function,
I will now get an error
when trying to load the messages page.
The reason for that is
that nextCache actually always returns a promise.
So it returns to cached data,
but wrapped in a promise.
Previously, get messages did not yield a promise.
Now, because I wrapped it with nextCache.
So with unstable_cache, it does,
and hence we must bring back the async keyword here
on the components that use get messages
and add await here,
and also do that in the layout
and have async await here as well.
With that added, the application works again,
and now you'll see that if I clear this
and restart the development server,
that if I reload this messages page, I got no log here.
So this log where I log that I'm fetching messages from
the database, I don't see that here
no matter how often I reload
because now indeed the data
that was retrieved from the database
is cached and is reused.
Now the nextCache function actually has another argument,
a second argument, which you should also specify,
and that's an array of cache keys,
which is then used internally to identify cached data.
For example, messages, it's up to you.
This is not to be confused with the tags you can assign.
You will see how to assign tags
to your own cached data later.
This is just used internally,
but with that, you can then make NextJS cache data
from your own data source.