redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

extraReducers 'ReferenceError: Cannot access before initialization' with inject

Open zz707 opened this issue 1 year ago • 3 comments

store.ts

export interface LazyLoadedSlices {}

export const rootReducer = combineSlices(
  appSlice,
  currentUserSlice,
).withLazyLoadedSlices<LazyLoadedSlices>();

projectEditSlice.ts

export const projectEditSliceLazy = createSlice({
  name: 'projectEdit',
  initialState,
  reducers: {
    setProjectCommonInfo: (),
  },
  extraReducers: (builder) => {
    builder
      .addCase(projectGetById.fulfilled, (state) => {
        state.isLoading = false;
      })
      .addCase(projectUpdateCommonInfo.fulfilled, (state) => {
        state.isLoading = false;
      });
  },
});

export const { actions: projectEditActions } = projectEditSliceLazy;

export const reducerWithProjectEditSlice =
  rootReducer.inject(projectEditSliceLazy);

projectUpdateCommonInfo.ts

export const projectUpdateCommonInfo = createAsyncThunk<...>
  ('project/update', async (updateData, thunkApi) => {
  const { extra, dispatch, rejectWithValue } = thunkApi;

  try {
    const response = await extra.api.patch<...>();
    ...
    dispatch(projectEditActions.setProjectCommonInfo(response.data));
  } catch {}
})

Only the await dispatch(projectGetById(id)); is called on the edit page and i recieve error ReferenceError: Cannot access 'projectUpdateCommonInfo' before initialization.

If I make a slice ordinary, without lazy loading and add it directly to the rootReducer, then everything works without errors.

Please tell me where my mistake is.

zz707 avatar Mar 25 '24 16:03 zz707

it sounds like you might have a circular dependency issue - could you share a repo?

EskiMojo14 avatar Mar 26 '24 11:03 EskiMojo14

could you share a repo?

Sorry, no. It confuses me that everything works without inject.

zz707 avatar Mar 28 '24 04:03 zz707

I'm having the same issue, and i'm don't have circular dependency

Deboracgs avatar May 16 '24 20:05 Deboracgs