[Vuejs]-Prefetching data with Nuxt to improve loading time

0👍

Use The fetch Method

<template>
  <h1>Stars: {{ $store.state.stars }}</h1>
</template>

<script>
export default {
  async fetch ({ store, params }) {
    let { data } = await axios.get('http://my-api/stars')
    store.commit('setStars', data)
  }
}
</script>

Remember to use Vuex to work well!


UPDATE: How to share the fetch function

1 – Create a file with the function:

// defaultFetch.js
module.exports = async function defaultFetch({ store, params }){
  // Put some developer magic here to make the code works for you
  let { data } = await axios.get('http://my-api/stars');
  store.commit('setStars', data);
}

2 – Import and use in other components

// amazingComoponent1.vue
<template>
  <h1>Stars: {{ $store.state.stars }}</h1>
</template>

<script>
import defaultFetch from "../utils/defaultFetch";
export default {
  fetch: defaultFetch
}
</script>



// amazingComoponent2.vue
<template>
  <h1>Stars: {{ $store.state.stars }}</h1>
</template>

<script>
import fetch from "../utils/defaultFetch";
export default {
  fetch,
}
</script>

UPDATE 2: How to use and configure axios intance

Very easy, update the defaultFetch.js:

// defaultFetch.js

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

module.exports = async function defaultFetch({ store, params }){
  // Put some developer magic here to make the code works for you
  let { data } = await instance.get('http://my-api/stars');
  store.commit('setStars', data);
}

Hope helps 🙂

Leave a comment