When utilizing combineSlices
with createAsyncThunk
condition
, I find it challenging to avoid circular dependency.
My store initiation thunk looks like this:
thunk.ts
export const initiateFx = createAsyncThunk<
InitiatePayload,
string,
{ state: RootState }
>(
'initiate-fx',
async (dashboardId, { dispatch, fulfillWithValue }) => {
const data = await fetchToSomeApi();
return fulfillWithValue(data);
},
{
condition: () => true
}
);
In addition, there is a lazy injected slice in my setup:
store.ts
declare module '@shared/redux/store' {
// comment: resolve typings for lazy loading slices
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface LazyLoadedSlices extends WithSlice<typeof slice> {}
}
export type State = {
data: Data;
isInitialized: boolean;
isLoading: boolean;
};
const initialState: State = {
data: null,
isInitialized: false,
isLoading: false,
};
export const slice = createSlice({
name: 'my-slice',
initialState,
reducers: {
reset: () => initialState
},
extraReducers: (builder) => {
builder.addCase(initiateFx.pending, (state) => {
state.isLoading = true;
});
builder.addCase(initiateFx.fulfilled, (state, action) => {
state.data = action.payload;
state.isInitialized = true;
state.isLoading = false;
});
},
selectors: {
selectIsInitialized: (state) => state.dashboardId,
selectIsLoading: (state) => state.isLoading,
selectData: (state) => state.data
}
});
export const { actions, selectors } = slice.injectInto(rootReducer);
The objective is to include a condition in the thunk to prevent unnecessary requests
// ...
{
condition: (_, { getState }) => {
const state = getState();
const isLoading = selectors.selectIsLoading(state);
const isInitialized = selector.selectIsInitalized(state);
return !isLoading && !isInitialized;
}
}
// ...
The issue of circular dependency arises: store.ts -> thunk.ts -> store.ts