Async Actionを待機するためのThunkDispatchでのawait
createAsyncThunk で作成したActionをdispatchする際は返り値の型がPromiseになるため、awaitしてThunk Actionの終了を待機できる
createAsyncThunk の型引数は <ReturnType, PayloadType, ThunkAPI>
ThunkAPI は基本的には { dispatch: AppDispatch; state: RootState } しとけばいいと思う
middlewareにちゃんと型を付けたら store.dispatch にMiddlewareを想定した適切な型が付くので、 store.ts で export type AppDispatch = typeof store.dispatch しておいた方がいい
middleware: getDefaultMiddleware() をした dispatch の型はこうなる
code:typescript
type AppDispatch = ThunkDispatch<any, null, AnyAction> &
ThunkDispatch<any, undefined, AnyAction> & Dispatch<AnyAction>
なので、こんなコードでStoreの復元を待機することができる
code:persist.ts
export const loadStore = createAsyncThunk<void, undefined, { dispatch: AppDispatch; state: RootState }>(
"persist/loadStore",
async (_: undefined, { dispatch }) => {
const restoredStore: Partial<RootState> = await pluginCall("fzf_preview#remote#store#restore_store")
dispatch(vimVariableModule.actions.restore(restoredStore.vimVariable))
dispatch(executeCommandModule.actions.restore(restoredStore.executeCommand))
}
)
code:handler.ts
export const callProcess = async (lines: Array<string>) => {
await dispatch(loadStore())
const executeCommand = createExecuteCommandSelector(store)()
runProcess(lines, executeCommand)
}