reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.73k stars 1.17k forks source link

extraReducers 'ReferenceError: Cannot access before initialization' with inject #4303

Closed zz707 closed 1 month ago

zz707 commented 7 months ago

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.

EskiMojo14 commented 7 months ago

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

zz707 commented 7 months ago

could you share a repo?

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

Deboracgs commented 5 months ago

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