0

I'm trying to do the following.

import axios from 'axios';
function testURL(url) {
  var data = axios.post(`http://localhost:4000/api/test`, { url } )
      .then(res => {
        return res.data;
      })
  return data
}

It's to be used in React JSX, something like {testURL(props.url)}. The issue I'm having is that it returns a promise, when really what I need it to do is return the response.

I'm not sure exactly where to put the return statements to get what I'm after. Do I need to make it blocking somehow?

cjm2671
  • 18,348
  • 31
  • 102
  • 161
  • Your only real option is to use the Promise as-is, you can't parse data retrieved asynchronously in a synchronous manner – CertainPerformance Feb 23 '19 at 20:16
  • What would you propose then? Use something other then axios that doesn't support promises? – cjm2671 Feb 23 '19 at 20:17
  • You should just use the Promise - call `.then` on the call of `testURL` – CertainPerformance Feb 23 '19 at 20:18
  • The difficult is when I do this, it seems to try to render the promise first, resulting in: `Uncaught Invariant Violation: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.` – cjm2671 Feb 23 '19 at 20:26
  • There are [many results](https://www.google.com/search?q="Objects+are+not+valid+as+a+React+child+(found%3A+[object+Promise])"), check them out - if not enough, ask a question about how to fix your React code (there's nothing wrong with your use of promises here) – CertainPerformance Feb 23 '19 at 20:30

0 Answers0