profile
viewpoint

Ask questionsA computed property name must be of type 'string', 'number', 'symbol', or 'any' with extraReducers

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;
    },
  },
reduxjs/redux-toolkit

Answer questions phryneas

@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.

useful!
source:https://uonfu.com/
answerer
Lenz Weber phryneas @mayflower Germany https://phryneas.de DevOp at @mayflower. Interested in react, typescript, security and nixos. (I know, a strange combination)
Github User Rank List