0

I currently trying to get myself familiar with react and the state of a component.

I am trying to create a component, use the constructor to initialise the state, do a get request to the server to get an array of object and finally I am trying to update the state of the component accordingly. But I end up with the following error and I can't understand the problem:

Objects are not valid as a React child (found: object with keys {title, content}).

My code looks like this:

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

class Display extends Component {

  constructor(){
    super();
    this.state = { posts: []}
  }

  componentDidMount(){
    this.fetchData();
  }

  fetchData(){
    const ROOT_URL = "http://localhost:5000";
    axios.get(`${ROOT_URL}/api/post`)
      .then(response => response.data.map(post => (
        {
        title: post.title,
        content: post.content
      }))
    )
    .then(
      posts => {
                this.setState({
                  posts
                })
               }
        )
   }

  render(){
    const { posts } = this.state;
    return (
      <div className="article">
        List of Posts: 
        {this.state.posts}
      </div>
    )
  }
}

export default Display;

Does anyone know what am I doing wrong?

Thanks

matami
  • 21
  • 1
  • 1
  • 2
  • `this.state.posts` is an array. You can't render an array like that. Read the doc. https://reactjs.org/docs/lists-and-keys.html – Striped Mar 19 '18 at 12:10

2 Answers2

1

this.state.posts is an object like

  {
    title: post.title,
    content: post.content
  }

and hence you can't render it direct like

  <div className="article">
    List of Posts: 
    {this.state.posts}
  </div>

You might as well render it like

 <div className="article">
    List of Posts: 
    {this.state.posts.map((post) => {
        return <div>
            <div>{post.title}</div>
            <p>{post.content}</p>
        </div>
    })
 </div>

above is assuming that content is also not an object or array. Check How to render an array of objects for more details

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Thank you - It solved my problem. For some reasons I thought that my problem was with this.setState({ posts }) – matami Mar 21 '18 at 10:39
0

You would need to iterate over the posts array and return the html you want to display

Something like this

List of Posts: 
    {this.state.posts.map(post=>(
      <div> 
        <span>{post.title}</span>
        <p>{post.content}</p>
      </div>
    ))}
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317