I am trying to pass token that comes from Redux store in an axios instance(useRequest). I want to pass the token while I am calling the instance
requestMethod.js
import axios from "axios";
const BASE_URL = "http://localhost:5000/e-mart/";
//Declaring a function to pass the Token dynamically.
export const userRequest =(TOKEN) => axios.create({
baseURL: BASE_URL,
header: { token: `Bearer ${TOKEN}` }, // Here the token comes dynamically
});
Products.js
import { userRequest} from "../requestMethods";
import { useDispatch, useSelector } from "react-redux";
const {accessToken} = useSelector((state) => state.user.currentUser);//accessing token from redux store
useEffect(() => {
const abortController = new AbortController();
const getProdcuts = async () => {
try {
const res = await publicRequest.get(
`products`,
{ signal: abortController.signal } // Here is where i want to pass the token from redux stroe
);
setProducts(res.data);
} catch (err) {
console.log(err.message);
}
};
getProdcuts();
return () => {
abortController.abort();
};
}, []);
If token is dynamic, don't pass it while create axios instance
// Axios instance
export const userRequest =(TOKEN) => axios.create({
baseURL: BASE_URL
})
// how to call with different dynamic tokens
await API.patch('products',
{ signal: abortController.signal },
{
headers: {
token: `Bearer ${TOKEN}`,
},
},
);