Search code examples
reactjsasynchronousreact-reduxaxiosredux-thunk

How to dispatch post data object using async thunk redux axios middleware


I am trying to dispatch a post of an object data using async redux axios middleware. I am getting 400 https response prob due to formatting. Here is what I have for my code. Any feedback is great!

import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

export const postResults = createAsyncThunk(
  'results/postResults',
  async ({ data: TestData[] }) => {
        const response = await axios.post(`${url}/data/results`, { data });
        return response.data;
  }
);

const sendData = async (data) => {
  try {
    data = {
      result: 'passed',
      data_id: [0]
    };
    await dispatch(postResults(data));
  } catch (err) {
      console.log(err);
  }
};

I am using sendData(data) in another function to trigger the event.

const processData = (e) => {
   //.....
   sendData(data);    
}

The output I am getting when I debug under xhr.js request.send(requestData):

requestData: "{\"data\":{\"result\":\"passed\",\"data_id\":[0]}}"

I think the formatting is an issue which I have tried to remove data so I can be read and sent its request as

requestData: "{\"result\":\"passed\",\"data_id\":[0]}"

Any thoughts or feedback!


Solution

  • figured out, I removed the { } so its like this:
    const response = await axios.post(${url}/data/results, data);