I recently started using redux-toolkit and started writing my reducers using the createSlice
following their docs.
One reducer, let's call it reducerA
, imports customAsyncFunction
to handle its callback, this function is created through createAsyncThunk
which in turn reads the RootState
when it calls thunkApi.getState()
, the problem now is that when RootReducer
is imported, reducerA
will be imported generating a circular reference.
Basically: RootReducer -> reducerA -> actions -> RootReducer -> ...
Below I attempt to simplify the problem.
// actions.ts file
import { RootState } from "./RootReducer";
export const customAsyncAction = createAsyncAction("myaction", async (_, thunkApi) =>
const state = thinkApi.getState() as RootState;
...
);
// reducerA.ts file
import { customAsyncAction } from "./actions";
const slice = createSlice({
...
extraReducers: {
[customAsyncAction.fulfilled.toString()]: ... // handles fulfilled action
}
});
export default slice.reducer;
// RootReducer.ts file
import reducerA from "./reducerA"
import reducerB from "./reducerB"
const reducers = combineReducers({
reducerA,
reducerB
});
export type RootState = ReturnType<typeof reducers>; // complains about circular reference
In this section of the documentation it's mentioned the likelihood of this happening and there are vague suggestions of splitting the code in files. However from all my attempts I can't seem to find a way to fix this problem.