1

I am trying to use data from a single object. Here is my code:

import React, { Component } from "react";
import axios from "axios";

class Home extends Component {
  state = {
    post: []
  }
  componentDidMount() {
    axios.get("https://jsonplaceholder.typicode.com/posts/1")
    .then(res => {
      console.log(res);
      this.setState({
        post: res.data
      })
    })
  }
  render() {
    const { post } = this.state;
    return (
      <p>{ post }</p>
    )
  }
}

export default Home;

I get the error:

Unhandled Rejection (Error): 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.

1
  • 1
    You are trying to render the JSON response object. Instead you should render the object properties for eg <p>{post.title}</p><p>{post.body}</p> etc. Commented Sep 4, 2021 at 16:38

1 Answer 1

2

The post value you keep in the state is a javascript object. You cannot directly put an object inside an html element. Either put a value from the object or stringify the object

...
return (
  <p>{post.title}</p>
)
...
return (
  <p>{JSON.stringify(post)}</p>
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.