Shadow Walker
Shadow Walker

Reputation: 1199

REACT - How to pass a function to an axios api call

I'm trying to avoid repeating part of the code that retrieves access token and passing it to my axios api.

I have created a separate file that contains a function that performs the retrieving of the token but when i pass that function method to axios api, it does not work. Meaning the token is not being retrieved from localStorage. Where i'm i going wrong?

My GET API method

import tokenConfig from "./token"
...

_refreshRecords() {
    axios
      .get("http://localhost:8000/api/accounts/employees_hr/", tokenConfig) <-- PASSING HERE
      .then((response) =>
        this.setState({
          employeesDetail: response.data.results,
        })
      );
    }

My Token file

// GET TOKEN
export default tokenConfig =>{

  // Headers
  const config = {
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json",
    },
  };

  // If there token, add to headers config
  if (localStorage.getItem("access")) {
    config.headers["Authorization"] = `JWT ${localStorage.getItem("access")}`;
  }

  return config;
};

Upvotes: 0

Views: 1682

Answers (2)

Adam Azad
Adam Azad

Reputation: 11297

You forgot to execute the tokenConfig in _refreshRecords.

Consider using the built-in interceptors provided by Axios. I normally do this in my API Axios instance.

// /services/api/index.js
import Axios from 'axios';

const api = Axios.create({
    baseURL: 'http://localhost:8000/api',
    timeout: 30000,
    headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
});

api.interceptors.request.use(
    config => {
        
        if (localStorage.getItem("access")) {
            config.headers.Authorization = `JWT ${localStorage.getItem("access")}`;
        }

        return config;
    },
    error => Promise.reject(error)
);

export default api;

And to use it in other components, you would import ../services/api and use it:

import API from '../services/api';


class App extends Component {

    _refreshRecords() {
         API.get('/accounts/employees_hr/').then(response =>
              this.setState({
                   employeesDetail: response.data.results,
              })
         );
    }

}

Upvotes: 2

macborowy
macborowy

Reputation: 1534

You must execute the tokenConfig function. Otherwise you'll pass a function instead of an object that get() function expects.

axios
  .get("http://localhost:8000/api/accounts/employees_hr/", tokenConfig())
  .then((response) =>
    this.setState({
      employeesDetail: response.data.results,
    })
  );

Upvotes: 2

Related Questions