redux 如何键入自定义createAsyncThunk Package

8xiog9wr  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(138)

我有这个thunk Package 器,我最初在js应用程序中使用。
因此,我很难弄清楚如何键入它,主要是因为thunkthunkApi类型:

export const asyncThunkHandleError = (
  typePrefix: string,
  thunk: any, // how to type this one and thunkAPI?
  errorMessage?: string
) =>
  createAsyncThunk(typePrefix, async (arg: any, thunkAPI: any) => {
    try {
      // actually call the thunk
      return await thunk(arg, thunkAPI);
    } catch (error: any) {
      // here we will dispatch the modal with the error message
      thunkAPI.dispatch(
        openModal({
          title: `Error in ${typePrefix}`,
          children: `${error instanceof Error ? error.message : 'Unknown error'}`,
        })
      );
      throw thunkAPI.rejectWithValue(error.response?.data || errorMessage);
    }
  });

它的调度方式如下:

// SomeComponent.tsx
dispatch(getPokemons());

thunk是这样 Package 的:

// actions/pokemons.ts
const getPokemons = asyncThunkHandleError(
  'pokemons/getPokemons',
  async (arg: any, thunkAPI: any) => {
    const someNetworkCall = await fetch('https://example.com');

    return someNetworkCall.json();
  },
  'An error occurred'
);

我一直在检查依赖文件,在路径.../@reduxjs/toolkit/src/createAsyncThunk.ts中发现了一些类型,如BaseThunkAPIGetThunkAPIAsyncThunkPayloadCreator等,但我不确定如何实现它,也不确定它是否正确。

slwdgvem

slwdgvem1#

好吧,我找到了一个类似here情况的解决方案,它甚至有一个操场:

import {createAsyncThunk,AsyncThunkPayloadCreator,AsyncThunk} from '@reduxjs/toolkit'

interface ThunkAPIConfig {}

export const createMyOwnAsyncThunk = <Returned, ThunkArg = any>(
  type: string,
  thunk: AsyncThunkPayloadCreator<Returned, ThunkArg>,    // <-- very unsure of this - have tried many things here
): AsyncThunk<Returned, ThunkArg, ThunkAPIConfig> => {
  return createAsyncThunk<Returned, ThunkArg, ThunkAPIConfig>(
    type,
    async (arg, thunkAPI) => {
      try {
        // do some stuff here that happens on every action
        return await thunk(arg, thunkAPI)
      } catch (err) {
        // do some stuff here that happens on every error
        return thunkAPI.rejectWithValue(null)
      }
    },
  )
}

相关问题