Reputation: 43
I'm currently developing a NUXT.JS application, which gets JSON data from an API (Storyblok).
I could do with a little input / best practice advice on how to store/cache the API response - so that the API isn't requested multiple times when skipping through the pages.
I've looked at a million and one articles and tutorials and they all come back to Redis. Which is probably a little over the top for what I need.
I've added what I've done so far below - minus storing/caching.
Any and all input would be appreciated.
<script>
export default {
asyncData (context) {
const version = context.query._storyblok || context.isDev ? 'draft' : 'published'
const fullSlug = (context.route.path === '/' || context.route.path === '') ? 'home' : context.route.path
return context.app.$storyapi.get(`cdn/stories/${fullSlug}`, {
version
}).then((res) => {
return res.data
}).catch((res) => {
if (!res.response) {
context.error({ statusCode: 404, message: 'Failed to receive content form api' })
} else {
context.error({ statusCode: res.response.status, message: res.response.data })
}
})
},
data () {
return {
story: { content: {} }
}
},
mounted () {
this.$storybridge(() => {
const { StoryblokBridge } = window
const storyblokInstance = new StoryblokBridge()
storyblokInstance.on('input', (event) => {
if (event.story.id === this.story.id) {
this.story.content = event.story.content
}
})
storyblokInstance.on(['published', 'change'], (event) => {
this.$nuxt.$router.go({
path: this.$nuxt.$router.currentRoute,
force: true
})
})
})
}
}
</script>
Upvotes: 1
Views: 2055
Reputation: 46604
You could use memoization if you do handle some big queries that may require a decent amount of time to compute. You can combine it with some Vuex comparison, to see if you need to refetch the data or not.
Browser's cache can do a good amount of work too: https://stackoverflow.com/a/68087754/8816585. I guess that it depends of the files and if you can have proper headers.
Nuxt's keep alive component based on Vue's one can also be somewhat useful, if you just want to toggle some components without refetching them every time.
SWR is an awesome implementation too! Here is the Vue counterpart. Meanwhile, it was pretty tricky to setup initially last time I tried too.
There are probably even more solutions for the frontend, but I only know those. And also, the right answer depends of your needs too.
Upvotes: 3