Search code examples
vue.jsaxiosnuxt.jsvuex

Nuxt.js - The best place for API calls


I'm new to Vue.js Nuxt and all front-end stuff.

I have a question about API calls. I'm not sure what is the right way, the best practice here.

I have a store. In that store, I have actions that are calling my API and sets state eg.

async fetchArticle({ state, commit }, uuid) {
    const response = await this.$axios.get(`articles/${uuid}/`)
    commit('SET_ARTICLE', response.data)
},

And that is fine it is working for one component.

But what if I want to just fetch the article and not changing the state.

To be DRY first thing that comes to my mind is to create the service layer that is fetching the data and is used where it is needed.

Is it the right approach? Where can I find some real-world examples that I can take inspiration from?


Solution

  • Using the repository pattern to abstract your API is definitely a good idea! Whether you use the @nuxtjs/axios module or the @nuxt/http module, you can pass either instance to your repository class/function. Below a real world example of an abstracted "repository.js" file.

    export default $axios => resource => ({
      index() {
        return $axios.$get(`/${resource}`)
      },
    
      create(payload) {
        return $axios.$post(`/${resource}`, payload)
      },
    
      show(id) {
        return $axios.$get(`/${resource}/${id}`)
      },
    
    
      update(payload, id) {
        return $axios.$put(`/${resource}/${id}`, payload)
      },
    
      delete(id) {
        return $axios.$delete(`/${resource}/${id}`)
      }
    
    })
    

    You can then create a plugin to initialize all different kinds of repositories for your endpoints:

    import createRepository from '~/path/to/repository.js'
    
    export default (ctx, inject) => {
      const repositoryWithAxios = createRepository(ctx.$axios)
    
      const repositories = {
        posts: repositoryWithAxios('posts'),
        users: repositoryWithAxios('users')
        //...
      }
    
      inject('repositories', repositories)
    }
    

    Further read: Organize and decouple your API calls in Nuxt.js