I want to create a global axios instance with an interceptor which adds a header with access token. The access token is stored in a cookie, but I can't figure out how to access the cookie inside the interceptor as it is not a react component.
I have tried creating the axios instance in a custom hook like this:
import React, { useEffect, useState } from "react";
import { useCookies } from "react-cookie";
import axios from "axios";
function useApiClient() {
const [cookies, setCookie] = useCookies(["token"]);
const [client, setClient] = useState(null);
useEffect(() => {
setClient(
axios
.create({
baseURL: "http://localhost:8080/api/",
responseType: "json",
})
.interceptors.request.use(
(config) => {
console.log("setting up");
if (cookies["token"] != null) {
config.headers.authorization = cookies["token"];
}
},
(error) => Promise.reject(error)
)
);
}, [client]);
return client;
}
export default useApiClient;
But when I try to call this using:
const client = useApiClient();
function attemptLogin() {
const credentials = {
username: username,
password: password,
};
client
.post("/authenticate", JSON.stringify(credentials), {
headers: {
"Content-Type": "application/json",
},
}).then(....)
I get below error:
TypeError: client.post is not a function
Can anyone help?
[client]in the useEffect. Also can you show how do you use client.post?withCredentials: truefor the axios config?