S.M_Emamian
S.M_Emamian

Reputation: 17383

How to re import a function - reactjs

I make a class to create an axios api service. inside this class I fetch token(I got it from server and set it on cookie) from cookie.

const api = axios.create({
  headers: {
    common: {
      'Content-Type': 'application/json'
    },
    post: {

    }
  }
});


const cookies = parseCookies()
const token = cookies.token;
if (token && token !== 'undefined') {
  api.defaults.headers.common['Authorization'] = 'Bearer ' + token
}

because I import this api service from above component:

import api from "../../../services/httpService";

after login user, for another api calls cookie is null .

I think I have two solutions:

  1. I pass token to each api call like:

      const config = {
         headers: { Authorization: `Bearer ${cookies.token}` }
     };
      api.get('profile',config).then((res) => {
    

I don't want use this solution.

  1. re-create api import (but I don't know how I can).

Upvotes: 0

Views: 79

Answers (1)

Viet
Viet

Reputation: 12787

When login success, you set token for cookies. And you should update a token for axios instance in this step.

// ... set token in cookies
api.defaults.headers.common['Authorization'] = 'Bearer ' + token

And you don't need this logic when create instance:

const cookies = parseCookies()
const token = cookies.token;
if (token && token !== 'undefined') {
  api.defaults.headers.common['Authorization'] = 'Bearer ' + token
}

Upvotes: 1

Related Questions