'How to export Axios.create in Typescript
I have this working:
export default axios.create({
baseURL: 'sample',
headers: {
'Content-Type': 'application/json',
},
transformRequest: [
(data) => {
return JSON.stringify(data);
},
],
});
but the problem is once I edited to be like this:
const API = () => {
const token = 'sample'
const api: AxiosInstance = axios.create({
baseURL: 'http://localhost:5000',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
transformRequest: [
(data) => {
return JSON.stringify(data);
},
],
transformResponse: [
(data) => {
return JSON.parse(data);
},
],
});
return api;
};
export default API;
I want it to be an arrow function so I can access the token inside the function.
The problem is once I start to import the arrow function it will create an error not reading POST method
import API from 'apis';
API.post
Is there a way to implement it like an arrow function but will not lose the type definitions or create an error?
Solution 1:[1]
You don't loose any type definitions, but you're not using your import as a function.
If you write API().post
it will work.
I would suggest doing the following:
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:5000',
headers: {
'Content-Type': 'application/json',
},
transformRequest: [
(data) => {
return JSON.stringify(data);
},
],
transformResponse: [
(data) => {
return JSON.parse(data);
},
],
});
import store from '../store'
const listener = () => {
const token = store.getState().token
api.defaults.headers.common['Authorization'] = token;
}
store.subscribe(listener)
export default api;
You can access the token here as well.
Solution 2:[2]
Just because this is the question you find when you look for my problem, if you use require
to import axios, to use the correct type definition you'll have to import ti like that:
const axios = require('axios').default
axios.create(...) // No error
This would give an error:
const axios = require('axios')
axios.create(...) // Error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Sharcoux |