0

I am using material-table with reactjs to create a data grid. I am filling the table with data from a previous HTTP request from an API and want to render the response of a second HTTP request in another column of that same table

render: rowData => this.Myfunction(rowData)

Myfunction(data){
  axios.post('/api/status', {
      payload:data
    })
    .then( res => {
        if(res.data[0] != undefined){
       return res.data[0].status
      }
      else{
          return 'Null'
      }
    })
    .catch(function (error) {
          console.log(error);
     });
   }
}

The data I send to myFunction works properly for each row, but I cannot return the response I get from my request with axios.

I also tried

return axios.post('/api/reviews', {
  payload:data
}) 

But I get an error:

Objects are not valid as a React child (found: [object Promise]). If you     meant to render a collection of children, use an array instead.
EAzevedo
  • 751
  • 2
  • 17
  • 46

1 Answers1

3

The issue is you are using promises in MyFunction but not returning it correctly. The following will set the value of output to undefined, because the return inside then is asynchronous.

function Component() {
  const data = {};
  const [output, setOutput] = useState({});

  useEffect(() => {
    setOutput(MyFunction(data));
  }, []);

  return <div>{ JSON.stringify(output) }</div>;
}

First, you need to return the promise from MyFunction.

function Myfunction(data) {
  return axios
    .post('/api/status', {
      payload: data
    })
    .then(res => {
      if (res.data[0] != undefined) {
        return res.data[0].status;
      } else {
        return 'Null';
      }
    })
    .catch(function(error) {
      console.log(error);
    });
}

Then handle the result of the promise using a then call.

function Component() {
  const [output, setOutput] = useState({});

  useEffect(() => {
    MyFunction(data).then(setOutput);
  }, []);

  return (
      <div>{ JSON.stringify(output) }</div>
  )
}
Cameron Downer
  • 1,839
  • 17
  • 26