2

When I use fetch in React I got this error:

'Error: Objects are not valid as a React child (found: object with keys {results, info})'

This is my code:

import React from "react";
import "./App.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: [],
      IsLoding: false,
    };
  }

  componentDidMount() {
    fetch("https://api.randomuser.me/")
      .then(response => response.json())
      .then(data => this.setState({
        data: data,
        IsLoding: true
      }));[enter image description here][1]
  }

  render() {
    return (
      <div>
        <h1>
          Hello
          {this.state.data}
        </h1>
      </div>
    );
  }
}

export default App;

the error [1]: https://i.stack.imgur.com/klKKP.jpg

When I try console.log(data) it's working but when I try to get the data to page not working.

Iván Pérez
  • 2,278
  • 1
  • 24
  • 49
Ahmed
  • 21
  • 2
  • what is the `data` that your API returns, and that you see in the console. (We can't see your console output.) Your `render` will only work if it's a simple string (or array of those), but it seems from the error that it's an object. – Robin Zigmond Jul 12 '20 at 20:39
  • Does this answer your question? [Objects are not valid as a React child. If you meant to render a collection of children, use an array instead](https://stackoverflow.com/questions/52428879/objects-are-not-valid-as-a-react-child-if-you-meant-to-render-a-collection-of-c) – devserkan Jul 12 '20 at 20:39
  • this is the API https://api.randomuser.me its should return names and gender , and nothing in the console – Ahmed Jul 12 '20 at 21:59
  • @Ahmed, check the question above. You can't render a whole object, you should use the properties. – devserkan Jul 12 '20 at 22:37

2 Answers2

1

You need to map the data, because you can't render an object.

For example if you wanna see only the genders try this:

{this.state.data.results.map(item => <p>{item.gender}</p>)} 

Or you could implement a user component that render the user information

{this.state.data.results.map(item => <User item={item}} />)}

Dont forget to add the key prop when mapping an array!

https://es.reactjs.org/docs/lists-and-keys.html

Nacho Zullo
  • 551
  • 3
  • 5
0

this.state.data gets populated with an object {results, info}, from there you can render only the properties that are strings or numbers, some examples

For arrays [], you will need to map them

{this.state.data.results.map(result => result.gender)} 

in this case, results is an array of objects, map will get one by one and store it in the variable result, and this will be an object

For objects {}, you will need to find the property you want to render

{this.state.data.info.results}

Now if what you want is to render the whole object as it is, you need to convert it to a string like this

<pre>{JSON.stringify(this.state.data, null, 4)}</pre>
ludwiguer
  • 2,177
  • 2
  • 15
  • 21