0

I'm new to react and I don't understand why I'm getting the following error while setting state on componentDidMount. I did a research on similar errors, and I understand that react wants to be fed with a number, not with a promise. However, I'm pretty sure I'm resolving to a number by writing .then(res => res.json().then(data => data). So I can't figure out where's the error from.

Uncaught 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.
    in p (created by Info)
    in div (created by Info)
    in Info

This is the function that I use to fetch a number:

const get_eth = wallet =>
  fetch(
    `https://api.etherscan.io/api?module=account&action=balance&address=${wallet}&tag=latest`
  )
    .then(res =>
      res.json().then(data => data["result"] / 10 ** 18)
    )
    .catch(err => console.log(err));

And this is the setState:

  componentDidMount() {
    this.setState({eth_q: get_eth("0x0975ca9f986eee35f5cbba2d672ad9bc8d2a0844")})
  }
JJJ
  • 32,902
  • 20
  • 89
  • 102
Συλχαν
  • 45
  • 1
  • 6
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JJJ Apr 29 '18 at 16:08
  • why don't you do a setState within promise resolve? .then(res => res.json().then(data => this.setState({eth_q: data["result"] / 10 ** 18))) . As in React anytime you update state the render triggers! – meteor Apr 29 '18 at 16:11

1 Answers1

0

I think you want:

const get_eth = wallet =>
  fetch(API)
    .then(res => res.json())
    .then(data => data["result"] / 10 ** 18)
    .catch(err => console.log(err));

That is, you're chaining .then() to your .json() instead of to your fetch().

Then, in your componentDidMount():

componentDidMount() {
  get_eth('0x0975ca9f986eee35f5cbba2d672ad9bc8d2a0844').then(res => {
    this.setState({ eth_q: res });
  });
}
Colin Ricardo
  • 16,488
  • 11
  • 47
  • 80