Home > Mobile >  How to solve Redux Toolkit circular dependency action -> selector -> reducer -> action (.fu
How to solve Redux Toolkit circular dependency action -> selector -> reducer -> action (.fu

Time:03-03

When defining my actions, reducer, and selectors I wanted to try to keep these in separate files so that my folder structure looks like this:

- store 
-- foo.actions.ts 
-- foo.reducer.ts 
-- foo.selectors.ts

In my foo.actions.ts file I define all of my actions which include AsyncThunk actions. Some of these actions reference selectors in the foo.selectors.ts file. e.g.

import { selectById } from "./foo.selectors.ts"

export const barAction = createAsyncThunk<IFoo, { foo: IFoo }, { state: IFooState, rejectValue: IFoo }>(
    FooActionTypes.Bar,
    async (payload: {foo: IFoo}, {getState, rejectWithValue}) => {
        const existingFoo = selectById(getState(), payload.foo.id);
        ...
    }
);

The foo.selectors.ts file references the foo.reducer.ts file to use the entityAdapter that is used to create the initial state of the reducer. e.g.

import { fooAdapter } from "./foo.reducer.ts"

export const { selectById } = fooAdapter.getSelectors();

foo.reducer.ts then references foo.actions.ts in the createReducer function to reference the thunk types.

import { barAction } from "./foo.actions.ts"

export const fooAdapter = createEntityAdapter<IFoo>(...);
const initialState = fooAdapter.getInitialState();

export const reducer = createReducer(initialState, builder => 
    builder
        .addCase(barAction.fulfilled, ...)
):

This creates a circular dependency of actions -> selectors -> reducer -> actions which in turn causes the error Cannot read properties of undefined (reading 'fulfilled')

Is there any way to fix this whilst still maintaining the folder structure or is it unavoidable to have the thunks and reducer in the same file?

CodePudding user response:

Adding a method body to your builder callback could already help.


export const reducer = createReducer(initialState, builder => {
    builder
        .addCase(barAction.fulfilled, ...)
}
);

Other than that you could move your entityAdapter out into a fourth file.

  • Related