I am currently using Axios to do API calls and a Redux store to keep my JWT tokens such as my access tokens.
Here is an example of what my current Axios instance looks like:
ProductionInstanceAPI.js
import axios from 'axios';
export default axios.create({
baseURL: `https://my.app/`,
});
And it is used like this in one of my React pages:
Predictions.js
import ProductionAPI from '../../ProductionInstanceAPI';
import { useSelector } from 'react-redux';
import { selectAccount } from '../../redux/features/account/accountSlice'
const Predictions = () => {
const accountInformation = useSelector(selectAccount);
useEffect(() => {
ProductionAPI.get('ml/get_linear_regressions/', { headers: {"Authorization": `Bearer ${accountInformation.accessToken}`}})
.then((response) => {
let data = response.data;
console.log(data);
}).catch(error => {
console.log(error);
})
}, [accountInformation.accessToken]);
}
However thought I hate having to do useSelector for all of my .js files that do an API call and then have to add in the information to my API calls.
I tried doing this, however though you can't use the useSelector hook outside of a React component.
ProductionInstanceAPI.js trying to use Redux store
import axios from 'axios';
import { useSelector } from 'react-redux';
import { selectAccount } from './redux/features/account/accountSlice'
const accountInformation = useSelector(selectAccount)
export default axios.create({
baseURL: `https://my.app/`,
headers: {"Authorization": `Bearer ${accountInformation.accessToken}`}
});
How do I somehow add the accessToken from my Redux store for all of my Axios calls? Is there a way to do this that is cleaner?
Thank you so much!