Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to solve Redux Toolkit circular dependency action -> selector -> reducer -> action (.fullfilled of undefined)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading