Reputation: 841
I'm getting started with React and i'm trying to just make a call to an api that returns an object and just print the result by saving it in the state. But for what the message says, I'm missing something in the initialisation of the state.
This is what I'm doing:
const apiAddress = 'https://jsonplaceholder.typicode.com/posts/1';
class Caller extends React.Component {
constructor(props) {
super(props)
this.state = { scene: ""}
}
ComponentWillMount () {
fetch(apiAddress)
.then((response) => {
return response.json()
})
.then((resource) => {
console.log(resource);
this.setState({ scene: resource })
});
}
render() {
return (
<div>
Res: {this.state.scene}
</div>
)
}
}
ReactDOM.render(
<Caller />,
document.getElementById('root')
);
The response is this object:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
And the error I'm getting is this one:
Objects are not valid as a React child (found: object with keys {userId, id, title, body}). If you meant to render a collection of children, use an array instead.
Upvotes: 0
Views: 219
Reputation: 355
It looks like you are trying to render a raw object, which I don't think is valid when rendering children in React.
Try printing object values separately:
...
render() {
const { userId, id, title, body } = this.state.scene
return (
<>
<div> User ID: {userId}</div>
<div> Id: {id}</div>
<div> Title: {title}</div>
<div> Body: {body}</div>
</>
)
}
...
Upvotes: 2