Nuxtjs Redis cache implementation for API calls inside components

Viewed 1429

I am using the plugin Nuxt Perfect Cache to server-side cache my QPI requests to an external service.

I am using the cacheFetch method on Component level and this component is loaded on a dynamic page (defined by its slug). When I navigate to the dynamic page, the API call is not cached in Redis, however when I reload the page, the caching happens as expected. Below is how my code is structured:

_slug.js (for /users)

<template>
  <h1>{{ user.name }}</h1>
  <Posts :author = user.id>
</template>

<script>
import Posts from '~/components/Posts.vue'
export default {
  components: { Posts },
  async asyncData({params}) {
    const user = await fetch(`/users/${params.slug}`)
    .then(res => res.json())
  }
}
</script>

And inside Posts.vue I use the perfect cache cacheFetch method to fetch the list of posts, something like:

props: ['author'],
async fetch() {
  this.posts = await this.$cacheFetch({ key:`user--#{this.author}--posts`, expire: 60 * 60 },
    async () => {
      return await fetch(`/users/#{this.author}/posts`).then(res => res.json())
    })
},
data() {
  return {
    posts: []
  }
}

When I load the user page directly in the browser, the json response for the posts is saved in Redis as expected. When I navigate from within the application using a NuxtLink, the user page is displayed correctly (including the posts), but no key is set or get from Redis.

How can I ensure the API calls are cached when users interact with the app?

1 Answers

redis is only available in server side not client side when you are navigating in client side you don't have access to redis you can set absolute link to render server side when user is navigating but I don't recommend this. the best solution is cache data in redis in your api.

Related