Dom
Dom

Reputation: 3444

Problem to import a generic Axios function

I have this JS file with 2 export:

 import axios from "axios";

const apiClient = axios.create({
    baseURL: 'http://localhost:8000',
    withCredentials: true,
});
 
function apiClientWithAuthorization() {

    const token = JSON.parse(localStorage.getItem('token'))
    return axios.create({
        baseURL: 'http://localhost:8000/api/v1',
        withCredentials: true,
        headers: {
            'authorization': `Bearer ${token.token}`
        }
    })
}

export { apiClient, apiClientWithAuthorization }

And I want to import one function in this another JS file :

import React from 'react'
import { apiClientWithAuthorization } from '../../../contexts/ApiClient'
import { useAuth } from '../../../contexts/AuthContext'

const ProfilePage = () => {

  const { user } = useAuth()

  
  apiClientWithAuthorization.get('users/' + user.id)
........

I have this error

TypeError: _contexts_ApiClient__WEBPACK_IMPORTED_MODULE_1__.apiClientWithAuthorization.get is not a function

I am beginning with JS / React, and I do not understand my error.

Upvotes: 0

Views: 230

Answers (2)

Ryan Le
Ryan Le

Reputation: 8412

You exported a function that returns an Axios instance, so you will need to invoke it first to get the instance then reference to the get method from that instance:

Change:

apiClientWithAuthorization.get('users/' + user.id)

TO:

apiClientWithAuthorization().get('users/' + user.id);

But this is not a good practice, because every time you want to make a get request, you will create another instance.

To solve this, create an instance from your exported function and reuse it:

const apiClient = apiClientWithAuthorization();

apiClient.get('users/' + user.id);

//Future usage
apiClient.get('user-data/' + user.id);

Upvotes: 2

Dipesh Chaulagain
Dipesh Chaulagain

Reputation: 105

import React from 'react'
import { apiClientWithAuthorization } from '../../../contexts/ApiClient'
import { useAuth } from '../../../contexts/AuthContext'

const ProfilePage = () => {

const { user } = useAuth()


apiClientWithAuthorization().get('users/' + user.id)

You need to call apiClientWithAuthorization method.

Upvotes: 3

Related Questions