Reputation: 1738
I have this thunk wrapper which I initally used in a js app.
Therefore, I'm struggling to figure out how to type it, mostly because of the thunk
and the thunkApi
types:
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);
}
});
It's dispatched like this:
// SomeComponent.tsx
dispatch(getPokemons());
The thunk is wrapped like so:
// 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'
);
I've been checking in the dependency files and kind of found something types like BaseThunkAPI
, GetThunkAPI
, AsyncThunkPayloadCreator
etc in the path .../@reduxjs/toolkit/src/createAsyncThunk.ts
but I'm not sure how to implement it or if it's even correct.
Upvotes: 2
Views: 1152
Reputation: 1738
Well, I found a solution for a similar case here, it even has a playground:
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)
}
},
)
}
Upvotes: 3