I want to receive data from redux toolkit's createAsyncThunk when dispatching.
But I don't know how to set the data type.
If no data type is specified, a warning line is displayed with a red line.
like this Screenshot
How do I specify the type?
this is my code
// commentinput is string and post.id is number
const commetsubmitfun = useCallback(() => {
dispatch(addComment({content: commentinput, postId: post.id}));
}, [dispatch, commentinput]);
export const addComment = createAsyncThunk(
'post/addComment',
async (data, {rejectWithValue}) => {
try {
// data: {content: "aaa", postId: 66}
const response = await axios.post(`/post/${data.postId}/comment`, data); // POST /post/1/comment
return response.data;
} catch (error: any) {
return rejectWithValue(error.response.data);
}
},
);
CodePudding user response:
You should declare type when calling createAsyncThunk
,
declare an interface for data
like this :
type DataType = {
content : string
postId : string
}
then add it here :
async (data : DataType, {rejectWithValue}) => {
You can read more here : https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk
CodePudding user response:
you specify the types in the createSlice file with either interface or type
eg:
interface Action {
type: string
payload: {
img: string
images: string[] | [] | null
}
}
type is always string, payload is what you put in the { } inside dispatch(addComment({content: ...payload, postId: ..payload}));
interface Action {
type: string
payload: {
content: string
postId: number //or if its possibly undefined/null postId?: number | null | undefined
}
}
const initialStateValue = {
post: null
}
reducers: {
addComment: (state: any = initialStateValue, action: Action) => {
state.post = action.payload;
},