Search code examples
javascriptreactjsreduxreact-reduxredux-toolkit

Unable to pass object in createAsyncThunk in Redux Toolkit


I am trying to pass two parameters in createProductReview action when submitHandler function runs. One is id and other one is an object containing two items. The problem is that I am unable to pass the object in createProductReview action. It gives undefine when I console log it in reducer function. I want to know how can I pass these two arguments without getting error. Please check out attached image for error

submitHandler function

const submitHandler = (e) => {
    e.preventDefault();
    dispatch(createProductReview({ id, { rating, comment } }));
  };

createProductReview

export const createProductReview = createAsyncThunk(
  'reviewProduct',
  async ({ productId, review }, thunkAPI) => {
    console.log(productId, review);
    try {
      const {
        userLogin: { userInfo },
      } = thunkAPI.getState();
      const config = {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${userInfo.token}`,
        },
      };
      await axios.post(`/api/products/${productId}/reviews`, review, config);
    } catch (error) {
      const newError =
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message;
      return thunkAPI.rejectWithValue(newError);
    }
  }
);

submitHandler error


Solution

  • In javascript, you need to pass keys to the object so it should be like this

    dispatch(createProductReview({ productId:id, review:{ rating, comment } }));
    

    Specially, when you are destructuring it in the function. Since destructure works by getting the object with its key.

    so for example:

    const x = {temp:"1"}
    const {temp} = x;
    console.log(temp);
    //1