Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createAsyncThunk: Error: addCase cannot be called with two reducers for the same action type

This error occurred when I connect actions to extraReducers My code is

export const fetchCountries = createAsyncThunk(
  `country`, 
  async (organizationId: string) => {

export const saveCountry = createAsyncThunk(
  `country`,
  async ({ } => {})

const regions = createSlice({
  name,
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder.addCase(fetchCountries.pending, isFetching);
    builder.addCase(fetchCountries.rejected, error);
    builder.addCase(fetchCountries.fulfilled, (state, action) => {});

    builder.addCase(saveCountry.pending, isFetching);
    builder.addCase(saveCountry.rejected, error);
    builder.addCase(saveCountry.fulfilled, (state, {payload}) => {});

and if I run I get this error: Error: addCase cannot be called with two reducers for the same action type

like image 856
Alexey Nikonov Avatar asked Jul 14 '21 09:07

Alexey Nikonov


3 Answers

This happens because in my actions there is few AsyncThunks actions with the same typePrefix.

So it must have different names:

export const fetchCountries = createAsyncThunk(
  `getCountry`, //<------ this first argument (name) must be unique
  async (organizationId: string) => {

export const saveCountry = createAsyncThunk(
  `postCountry`,
  async ({ } => {})

like image 59
Alexey Nikonov Avatar answered Oct 18 '22 01:10

Alexey Nikonov


In my case, the same error message was show, but it was a different mistake:

.addCase(setAddress.pending, (state, action) => {
    state.setAddressStatus = 'Pending';
})
.addCase(setAddress.fulfilled, (state, action) => {
    state.setAddressStatus = 'Fulfilled';  
})
.addCase(setAddress.fulfilled, (state, action) => { // I repeated fulfilled 
    state.getAddressesStatus = 'Rejected';
    console.error(action.error);
})
            

It took me some minutes to find the problem, may help someone.

like image 45
Bruno Silva Avatar answered Oct 18 '22 00:10

Bruno Silva


On CreateAsycThunk you have mentioned both the string of the same name it should be like this

export const fetchCountries = createAsyncThunk(
  `country`, 
  async (organizationId: string) => {

export const saveCountry = createAsyncThunk(
  `saveCountry`,
  async ({ } => {})

const regions = createSlice({
  name,
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder.addCase(fetchCountries.pending, isFetching);
    builder.addCase(fetchCountries.rejected, error);
    builder.addCase(fetchCountries.fulfilled, (state, action) => {});

    builder.addCase(saveCountry.pending, isFetching);
    builder.addCase(saveCountry.rejected, error);
    builder.addCase(saveCountry.fulfilled, (state, {payload}) => {});
like image 1
Anuj Avatar answered Oct 18 '22 00:10

Anuj