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;
},
},
Correct - the "Usage with TypeScript" docs page tells you to use the "builder callback" notation for extraReducers to help with this.
@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
Most helpful comment
Correct - the "Usage with TypeScript" docs page tells you to use the "builder callback" notation for
extraReducersto help with this.