We can use the fetch method to fill the store state before a page is rendered. It works the same as the asyncData method, which we have already covered – it is called each time before a component is loaded. It is called on the server side once and then on the client side when navigating to other routes. Just like asyncData, we can use async/await with the fetch method for asynchronous data. It is called after the component is created, so we can access the component instance through this in the fetch method. So, we can access the store through this.$nuxt.context.store. Let's create a simple Nuxt app using this method with the following steps:
- Request the list of users from a remote API asynchronously with the fetch method in any page, as follows:
// pages/index.vue
import axios from 'axios'
export default {
async fetch () {
const { store } = this.$nuxt.context
await store.dispatch('users/getUsers')
}
}
- Create a user module...