Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to import module to external file #101

Closed
lukasborawski opened this issue Feb 12, 2018 · 16 comments
Closed

How to import module to external file #101

lukasborawski opened this issue Feb 12, 2018 · 16 comments

Comments

@lukasborawski
Copy link

lukasborawski commented Feb 12, 2018

So, let's say that I'm using axios module and extending it as a plugin. Now i need to import it to the external api.js file to define methods to fetch some data.

plugins/axios.js

export default function ({ $axios, app, store, redirect, route }) {
  $axios.defaults.baseURL = process.env.baseUrl
  ...

api/api.js

import axios from '@nuxtjs/axios'

export default axios

and some api file

api/feed.js

import api from './api.js'

export default {
  getPosts (params) {
    return api.get
    ...

How to do this? Got undefined errors ...

cc @pi0

This question is available on Nuxt.js community (#c88)
@husayt
Copy link

husayt commented Feb 12, 2018

I was just going to ask the same question. Additional question would be then how to use those apis from pages/vuex actions?

Basically, what is the best way to refer to axios from plugins or other js files?
import axios from "axios" does only provide blank axios instance, not related to configured one.

@lukasborawski
Copy link
Author

@pi0 @atinux @alexchopin can you guys help with this one?

@lukasborawski
Copy link
Author

@husayt here you will find nice solution, tested, working.

#28

Closing.

@husayt
Copy link

husayt commented Feb 15, 2018

@lukasborawski I think the following solution is far more elegant.

/plugins/api.js

const apiFactory = axios => ({
  getUsers(period = "Today") {
    return axios.get(`api/users`)
  },
  getProducts() {
    return axios.get(`/api2/products`)
  }
})

/*
** Executed by ~/.nuxt/index.js with context given
** This method can be asynchronous
*/
export default ({ $axios }, inject) => {
  // Inject `api` key
  // -> app.$api
  // -> this.$api in vue components
  // -> this.$api in store actions/mutations
  const api = apiFactory($axios)
  inject("api", api)
}

then use it like this (remember to register api.js in plugins in nuxt.config.js)

  async asyncData({ app }) {
    let { data } = await app.$api.getProducts()
...
  },

husayt added a commit to husayt/axios-module that referenced this issue Feb 15, 2018
Following discussion [here](nuxt-community#101) I thought it would be good to provide api definer feature from nuxt/axios module itself. This is a common pattern and putting it here perfectly fits in Nuxt way of doing things.

UseCase: Many prefer to define their api in a file and use that rather than calling axios directly.

This patch makes it very  easy.
Basically, user would define the api in a file e.g. `api-def.js`
```
export default axios => ({
  getOrders(period = "Today") {
    return axios.get(`api/orders?period=${period}`)
  },
  getUsers() {
    return axios.get(`/api/users`)
  }
})
```
then in nuxt.config.js
```
import apiFactory from "./api-def.js"
....
axios: {
    ....
    api: { factory: apiFactory }
  },
```
and that is it. Api woulld be available to plugins, actions, mutators and components
```
 -> app.$api or ctx.$api
 -> this.$api in vue components
 -> this.$api in store actions/mutations
```

This looks so much better
```
async asyncData({ api }) {
    let { data } = await $api.getOrders()
    return { orders: data }
  },
```
@husayt
Copy link

husayt commented Feb 15, 2018

I also suggested this as an addition to axios module

@bovas85
Copy link

bovas85 commented Mar 2, 2018

I'd recommend this above to be added with some config to avoid complexity

@husayt
Copy link

husayt commented Mar 2, 2018

@bovas85 this in the plan. @pi0 is working on adding this to nuxt axios module. Will be really cool

@bovas85
Copy link

bovas85 commented Mar 2, 2018

Great stuff :)

@tim-yao
Copy link

tim-yao commented Apr 11, 2018

@husayt I couldn't make your code work, keep saying Cannot read property 'getTest' of undefined. getTest is my version of your getProducts. Do you know why?

@husayt
Copy link

husayt commented Apr 12, 2018 via email

@tim-yao
Copy link

tim-yao commented Apr 16, 2018

It's a private repo, I am not able to share with you. But I used exactly same code as you posted. Thanks anyway @husayt
However I used other work above around in #101 (comment) and it works for me.

@yob-yob
Copy link

yob-yob commented Jan 29, 2020

Hi, I know that this thread is really old now. so yeah I'm wondering if this is still the best and most clean solution for this problem?

I'm Referring to the fix that @husayt made -- Husayt's Fix

I'm currently using this as my solution last time. it has been 2 years now and I wanted to update my code to be more readable and much easy to document and test.

@husayt
Copy link

husayt commented Jan 31, 2020

@MerrySean it still works for me too. I have seen some other approaches, but this is by far teh most simple one and works like a brick.

@manniL
Copy link
Member

manniL commented Feb 9, 2020

I'm also using the same technique, described a bit more in detail in my blog post

@husayt
Copy link

husayt commented Feb 10, 2020

Thanks @manniL, but isn't it now recommended to use nuxt http module instead of axios one? From what I understand the latter is not going to be supported moving forward. Although, that doesn't change the main point of the article, still is good to know

@ubay1
Copy link

ubay1 commented Aug 7, 2022

just import this in js file
import axios from 'axios/index';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants