https://stackblitz.com/edit/react-ts-rkekhf?file=app/redux/asyncThunkFromFetch.ts
We use the following helper to create thunks:
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios, { AxiosPromise, AxiosResponse } from 'axios';
import { store } from './store';
export const createAsyncThunkFromAPI = <ResponseSchema, RequestParams>(
typePrefix: string,
apiFunction: ApiFunction<RequestParams, ResponseSchema>
) => {
return createAsyncThunk<ResponseSchema, RequestParams>(
typePrefix,
async (args, thunkApi) => {
try {
const response = await apiFunction(args);
return response.data;
} catch (e) {
return thunkApi.rejectWithValue(e);
}
}
);
};
type ApiFunction<RequestParams, ResponseSchema> = (
axiosParams: RequestParams
) => AxiosPromise<ResponseSchema>;
export const getMobileOperatorsAPI = (): Promise<AxiosResponse<string[]>> => {
return axios.get('https://api.com');
};
export default createAsyncThunkFromAPI;
const sliceName = 'mobile-operators';
export const fetchMobileOperators = createAsyncThunkFromAPI(
`${sliceName}/fetchMobileOperators`,
getMobileOperatorsAPI
);
store.dispatch(fetchMobileOperators()); //Expected 1 arguments, but got 0.ts(2554)
store.dispatch(fetchMobileOperators({})); //Ouch!!!
One thing I hate about it, you cannot pass zero arguments to a thunk function created by the helper. However in our case it's still more convenient to use it instead of bare createAsyncThunk
from @redux/toolkit
I tried to make a default parameter for payload creator with no success. But I don't really understand what I'm doing here.
How to tweak createAsyncThunkFromAPI
to infer args
from API function?
How to implement the same idea in a proper way?
What knowledge do I miss to be able to resolve this problem by myself?