This is another scenario that helped me figure out how asynchronous operations works and to implement my code around it.
As I was going through the Nuxt 3 Fundamentals course on Vueschool.io in March 2023, in a lesson, we are introduced to useAsyncData
. It provides an option to work in a lazy mode.
In the Nuxt docs, I’ve found this example that I didn’t follow all the way, my bad, but it allowed me to understand the mechanism.
The example
Let’s take this example:
|
|
I used it on a movie search page and each time I browsed to it directly, it worked, loading the movies.
If I browser first to the home page for example and then the search page, I would get a blank page…
Why is that?
The solution
The problem is at the last line of the search
method.
If you log in the console fetchIsPending
and apiSearchResponse
, the first equals to true
and the second equals to undefined
.
It makes sense since it is lazy loading the data requested.
When the fetchIsPending
will turn into a truthy value apiSearchResponse
will contain an instance of ApiSearchResponse
.
How do you watch for that change?
Like so:
|
|
However, you may have noticed the option getCachedData
used on useLazyAsyncData
.
If you stop by adding the watch
and navigate to another page and come back the search page, it will be blank.
In fact, Nuxt returns the cached response, but the code doesn’t use this cached value.
So you need to add a check:
|
|
There you have it: you handle both first request and cached request and the user is happy to use your application!
Credit: Photo by Priscilla Du Preez on Unsplash.