Redux-toolkit: A computed property name must be of type 'string', 'number', 'symbol', or 'any' with extraReducers

Created on 4 Apr 2020  路  5Comments  路  Source: reduxjs/redux-toolkit

I create an async action using createAsyncThunk :

export const updateAffectedCase = createAsyncThunk(
  'affectedCases/update',
  async (caseToUpdate: AffectedCaseToUpdate, { rejectWithValue }) => {
    try {
      const updatedCaseId = await resolveCaseApi(caseToUpdate);
      return updatedCaseId;
    } catch (error) {
      let errorMessage = "Internal Server Error";
      if (error.response) {
        errorMessage = error.response.data.message;
      }
      return rejectWithValue(errorMessage);
    }
  }
)
const affectedCases = createSlice({
  name: 'affectedCase',
  initialState,
  extraReducers: {
    [updateAffectedCase.fulfilled]: (state, action: PayloadAction<number>) => {
      state.cases = state.cases.filter(c => c.caseId !== action.payload)
    },
    [updateAffectedCase.rejected]: (state, action: PayloadAction<string>) => {
      state.error = action.payload;
    },
  },
})

I got this error:

A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)

I fixed it only if I changed to :

extraReducers: {
    [updateAffectedCase.fulfilled.toString()]: (state, action: PayloadAction<number>) => {
      state.cases = state.cases.filter(c => c.caseId !== action.payload)
    },
    [updateAffectedCase.rejected.toString()]: (state, action: PayloadAction<string>) => {
      state.error = action.payload;
    },
  },

Most helpful comment

All 5 comments

@levenleven even if this were possible on TSs side, that wouldn't solve the underlying problem that the object notation for extraReducers would still be completely type-unsafe.
Please use the builder notation for TypeScript as only that allows TS to correctly infer the case reducer arguments from the action type.

const dataReducer = createReducer(initialState, {
    [dataActions.getAllDataSuccess.type]: (state, { payload: { data } }) => {
        state.dataList = data;
    },
});

@callamwilliams yes that is possible but we explicitly recommend not to do that and to use the builder notation instead. See the comment from Mark above: https://github.com/reduxjs/redux-toolkit/issues/478#issuecomment-609072266

Was this page helpful?
0 / 5 - 0 ratings

Related issues

emil14 picture emil14  路  3Comments

Izhaki picture Izhaki  路  3Comments

amankkg picture amankkg  路  4Comments

Brodzko picture Brodzko  路  4Comments

fdjones picture fdjones  路  4Comments