I am trying to use the token from my redux store inside my Axios instance. I tried importing the store but I am getting the and error saying _app_store__WEBPACK_IMPORTED_MODULE_1__.default is undefined. Please how do I solve this?
This is my code.
store.js
import { configureStore, combineReducers } from "@reduxjs/toolkit";
import authReducer from "../features/auth/authSlice";
import cartReducer from "../features/cart/cartSlice";
import {
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from "redux-persist";
import storage from "redux-persist/lib/storage";
const persistConfig = {
key: "root",
storage,
};
const reducers = combineReducers({
auth: authReducer,
cart: cartReducer,
});
const persistedReducer = persistReducer(persistConfig, reducers);
const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
});
export default store;
Then this is my axios instance file.
api.js
import axios from "axios";
import store from "../app/store";
const token = store.getState().auth.token;
const api = axios.create({
baseURL: process.env.REACT_APP_API_URL,
headers: {
Authorization: token,
},
});
export default api;
Apparently, I was trying to use the store before it was initialized. So I just created an interceptor for the Axios instance and called the store in there.
api.js
import axios from "axios";
import store from "../app/store";
const api = axios.create({
baseURL: process.env.REACT_APP_API_URL,
});
api.interceptors.request.use((config) => {
const token = store.getState().auth.token;
config.headers = {
Authorization: token ? `Bearer: ${token}` : null,
};
return config;
});
export default api;