API: The fetch Method

The fetch method is used to fill the store before rendering the page, it's like the asyncData method except it doesn't set the component data.

  • Type: Function

The fetch method, if set, is called every time before loading the component (only for page components). It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes.

The fetch method receives the context object as the first argument, we can use it to fetch some data and fill the store. To make the fetch method asynchronous, return a Promise, Nuxt.js will wait for the promise to be resolved before rendering the component.

Warning: You don't have access of the component instance through this inside fetch because it is called before initiating the component.

Example of pages/index.vue:

  1. <template>
  2. <h1>Stars: {{ $store.state.stars }}</h1>
  3. </template>
  4. <script>
  5. export default {
  6. fetch ({ store, params }) {
  7. return axios.get('http://my-api/stars')
  8. .then((res) => {
  9. store.commit('setStars', res.data)
  10. })
  11. }
  12. }
  13. </script>

You can also use async/await to make your code cleaner:

  1. <template>
  2. <h1>Stars: {{ $store.state.stars }}</h1>
  3. </template>
  4. <script>
  5. export default {
  6. async fetch ({ store, params }) {
  7. let { data } = await axios.get('http://my-api/stars')
  8. store.commit('setStars', data)
  9. }
  10. }
  11. </script>

Vuex

If you want to call a store action, use store.dispatch inside fetch, make sure to wait for the end of the action by using async/await inside:

  1. <script>
  2. export default {
  3. async fetch ({ store, params }) {
  4. await store.dispatch('GET_STARS');
  5. }
  6. }
  7. </script>

store/index.js

  1. // ...
  2. export const actions = {
  3. async GET_STARS ({ commit }) {
  4. const { data } = await axios.get('http://my-api/stars')
  5. commit('SET_STARS', data)
  6. }
  7. }

Listening to query string changes

The fetch method is not called on query string changes by default. If you want to change this behavior, for example when building a pagination component, you can setup parameters that should be listened to through the watchQuery property of your page component. Learn more on the API watchQuery page.