I am trying to create and axios instance so that I don't have to write Authorization header on every request. I am storing access token on localStorage.
I tried creating a file axiosInstance.ts
import axios, { AxiosInstance } from "axios"
const service = axios.create({
baseURL: "http://localhost:5000/",
headers: {
Authorization: localStorage && localStorage.getItem("token")
? `Bearer ${localStorage.getItem("token")}`
: "",
},
})
export default service
But it throws localStorage is not defined error.
So I tried to make this a custom hook like this
useAxios.ts
function useAxios() {
const [axiosInstance, setAxiosInstance] = useState<null | AxiosInstance>(null)
useEffect(() => {
const service = axios.create({
baseURL: "http://localhost:5000/",
headers: {
Authorization: localStorage.getItem("token")
? `Bearer ${localStorage.getItem("token")}`
: "",
},
})
setAxiosInstance(service)
}, [])
return axiosInstance
}
export default useAxios
And when i tried to use it like this it threw an error which says service.post is not a function
So when i log the service/axiosInstance it logs a get request promise to baseURL. I am not sure what i am doing wrong.