flinch85
flinch85

Reputation: 370

Using data from API JSON object using Axios and React

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.

Upvotes: 1

Views: 2584

Answers (1)

İbrahim Akar
İbrahim Akar

Reputation: 357

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>
)

Upvotes: 2

Related Questions