Search code examples
vue.jsdependency-injectionnuxt.jsasyncdata

How to access a injected repository from a component's method


Lets say we injected this repository on a plugin/service-container.js

import nodeFetch from 'node-fetch'
import { AbortController as NodeAbortController } from 'node-abort-controller'

import HttpClient from '@/services/httpClient'
import PostRepository from '@/repositories/posts'


export default ({ app }, inject) => {
  if (!process.client || app.context.env.NUXTJS_DEPLOY_TARGET === 'server') {
    inject('postRepository', postRepository)
  }
}

I have always acceded to API repositories from the asyncData method, like so:

export default {
  async asyncData ({ $postRepository,  }) {
    const posts = await $postRepository.getAllPaginated(page, 11)
    return {
      posts,
    }
  }
}

But I need to access to it in a method, this is actually working but:

  • I doesn't look the right way because i'm caching in the component's data()
  • It fires this lint error:

Async method 'asyncData' has no 'await' expression.eslintrequire-await

What's the right way? I Can't find it online (the only examples I found involved using the Store)

export default {
  async asyncData ({ $postRepository }) {
    this.$postRepository = $postRepository 
  },
  methods: {
    async loadMore () {
      if (this.page < this.posts.numPages) {
        const posts = await this.$postRepository.getAllPaginated(this.page + 1, 11)
      }
    }
  }
}

Solution

  • It seems that an injected dependency can be accessed (in this case) with simply this.$postRepository inside any method so I didn't even need that asyncData