从thunkAction调度另一个thunkAction

时间:2020-10-09 06:34:45

标签: javascript reactjs redux redux-toolkit

我在React App中使用redux-toolkit,我有这样的情况:

  1. 从deleteEntites thunkAction发送API调用以删除一些 数据库中的实体
  2. 发送getAllEntities thunkAction或发送另一个API调用以获取Fresh实体 清单?

问题是在deleteEntities API调用成功后我是否应该调度getAllEntities thunkAction?(如果是,怎么办?)

OR

我应该像在getAllthunkAction.fullfilled中一样发送getAllEntities API调用并在deletethunkAction.fullfilled reducer中重复操作吗?

    //queryParams are no longer needed
    export const getDevices = createAsyncThunk('devices/getDevices', 
        async (thunkAPI:any) => {       // have to find the datatype of thunkAPI
        try {
            const response=await requestFromServer.getAllDevices();
            return response.data;
        } catch (err) {
            // Use `err.response.data` as `action.payload` for a `rejected` action,
            // by explicitly returning it using the `rejectWithValue()` utility
            return thunkAPI.rejectWithValue(JSON.stringify(err.response.data))
        }  
    })

    // Delete one/many devices with ids and then from entities list
    export const deleteDevices = createAsyncThunk('devices/deleteDevices', 
        async (ids:any, thunkAPI:any) => {       // have to find the datatype of thunkAPI
        try {
          const deleteResponse = await requestFromServer.deleteDevices(ids);
          // Is this OK or I should dispatch getDevices thunk here? a bad practice I guess? 
          const getResponse = await requestFromServer.getAllDevices();
          return getResponse.data;
        } catch (err) {
          // Use `err.response.data` as `action.payload` for a `rejected` action,
          // by explicitly returning it using the `rejectWithValue()` utility
          return thunkAPI.rejectWithValue(JSON.stringify(err.response.data))
        }
    })

然后在createSlice的extraReducer中

/// The same reducer logic will be copied to devicesThunks.deleteDevices.fulfilled
.addCase(devicesThunks.getDevices.fulfilled, (state, action) => {
        const entities = action.payload;
        .
        .
        .
        return devicesAdapter.setAll({
          ...state,
          listLoading: false,
          .
          .
        },
          entities);

0 个答案:

没有答案