Sometimes when I run loadPosts dispatch, I don't send any data, sometimes I send lastId data to same loadPosts disaptch.
At this time, I don't know how to define the type of data in createAsyncThunk . When I run my code I get a red warning in loadPosts.
like this Screenshot
it says Expected 1 arguments, but got 0.
How can i fix my code?
this is my code
dispatch(loadPosts());
dispatch(loadPosts(lastId:lastId));
export const loadPosts = createAsyncThunk(
'post/loadPosts',
async (data: any, thunkAPI) => {
try {
const response = await axios.get(`/post?lastId=${data?.lastId || 0}`);
return response.data;
} catch (error: any) {
return thunkAPI.rejectWithValue(error.response.data);
}
},
CodePudding user response:
Make the data
argument optional:
async (data: any?, thunkAPI) => {
CodePudding user response:
RTK Docs: https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk
export const loadPosts = createAsyncThunk<
YourReturnType,
{
lastId: number;
} | void,
{ state: AppStore }
>('post/loadPosts', async (data, thunkAPI) => {
try {
const response = await axios.get(`/post?lastId=${data?.lastId || 0}`);
return response.data;
} catch (error) {
return thunkAPI.rejectWithValue(error.response.data);
}
});