Working on the backbone of a new RN app, I found myself in the following code state:
src/redux/index.ts
(who builds and exports the store) imports rootReducer
file, to configureStore
with it.const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
reducer: persistedReducer,
/* middleware definitions */
});
rootReducer
imports userReducer
to add it to reducers list with combineReducers
.const rootReducer = combineReducers({
/* some reducers */
user: userReducer,
});
userReducer
imports serverApi
to be able to make api calls with thunks.export const registerUser = createAsyncThunk(
'user/register',
async ({ country, number }: loginDataType) => {
const response = await serverApi.post('/register', { country, number });
return response.data;
},
);
serverApi
imports store
to get the token
from a user and set it in an Axios interceptor.instance.interceptors.request.use(
async config => {
const { token } = store.getState().user;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
);
And store is exported in src/redux/index.ts
as I said. There you go, this is the cycle. React throws me a warning like, come on man, don't do that. Where did I go wrong or what could I do differently?
So, the docs actually give the answer to this use case.
https://redux.js.org/faq/code-structure#how-can-i-use-the-redux-store-in-non-component-files
Basically instead of importing the store in the api file, we inject it from the store file itself :
export const injectStore(_store) {
store = _store
}
And in the store file :
injectStore(store);