1

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

enter image description here

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);
        }
      },
    );

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

if i have another dispatch like this dispatch(loadPost({postId: post.id})); can i reuse this DataType?? type DataType = { content : string postId : string }
you should just make the "content" not required change it to this : DataType = { content?: string postId : string } by adding a question mark
0

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;
    },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.