I am trying to translate a react native app(MobX) to a reactJS app and I want to use react hooks and context(with localStorage) for state management. I have a mainStore file:
export const MainStore = () => {
const AppContext = createContext();
const initialState = {
...
}
const reducer = (state, action) => {
return { ...state, ...action };
}
const [ initState, setInitState ] = useLocalStorage('state', initialState);
const [ state, dispatch ] = useReducer(reducer, initState);
const { getAssetData } = assets();
const getInstMetaData = async () => {
const params = {
asset_type_name: "...",
with: "..."
};
return getAssetData(params);
};
const checkForRefreshTokenUpdate = async () => {
...
}
return {
AppContext,
initialState,
state,
dispatch,
reducer,
checkForRefreshTokenUpdate,
getInstMetaData
};
My asset file is this:
import { interceptedAxios } from "./axios/config";
import { buildUrl } from "./utils/urls";
import { getAccessToken, getBaseUrl } from "./index";
const assets = () => {
const { customAxios } = interceptedAxios();
/**
* Fetches asset data.
* @returns
*/
const getAssetData = async (params) => {
const url = buildUrl({
baseUrl: getBaseUrl(),
endpoint: "/api/asset",
params
});
const reqOpts = {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${getAccessToken()}`
}
};
return customAxios.get(url, reqOpts).then(res => { res.data });
};
return { getAssetData }
}
export { assets };
and my interceptedAxios:
import axios from "axios";
import { MainStore } from "../../stores/mainStore";
import { getBaseUrl } from "../index";
export const interceptedAxios = () => {
// Create axios instance for customization and import this instead of "axios"
const customAxios = axios.create();
const { checkForRefreshTokenUpdate } = MainStore();
customAxios.interceptors.request.use(async (config) => {
if (config.url.includes(getBaseUrl()) && config.headers["Authorization"] != null) {
await checkForRefreshTokenUpdate()
.then((token) => {
if (token != null) {
config.headers["Authorization"] = `Bearer ${token}`;
}
});
}
return config;
},
(error) => {
return Promise.reject(error);
});
return { customAxios }
}
The error is: RangeError: Maximum call stack size exceeded, on running the app. I know that the fault that is that I am using MainStore() in inreceptedAxios. I am making something like a circle in dependencies, but I can't think of another way to do it and somehow i need to use checkForRefreshTokenUpdate. Any thoughts?