我有一个createSlice
从 redux-toolkit 生成的 redux-thunk reducer,名为getOne
.
getOne
从 API 获取并调度加载状态的操作,( startedLoading
, finishedLoading
, errorLoading
)。
我还想调用在insert
使用结果数据调用的同一切片中创建的另一个 actionCreater。或者直接从getOne
reducer更新状态。
import { createSlice } from "@reduxjs/toolkit"
import { startedLoading, finishedLoading, errorLoading } from '../slices/loadingSlice'
const apiEndpoint = "/api/v1"
const fetchOptions = { headers: { "Content-Type": "application/json" } }
const createModelSlice = function (modelName) {
return createSlice({
name: modelName,
initialState: {byId: {}},
reducers: {
insert: (state, action) => {
// ...
},
getOne: (state, action) => async (dispatch) => {
// ...
try {
const response = await fetch(/* */)
// How would I update the store here?
// 1. reference the insert actionCreater somehow.
dispatch(insert({id: id, data: response))
// 2. construct the action manually
dispatch({action: `${modelName}/insert`, payload: {id: id, data: response))
// 3. Mutate the state here and rely immer. (I'm not sure exactly how that works)
state[modelName].byId[id] = response
dispatch(finishedLoading({ key: /* */ }))
} catch (error) {
dispatch(errorLoading({ key: /* */ }))
}
},
// ...
}
})
}