1

I am trying to understand what I am doing wrong with accessing and displaying part of my retrieved JSON object. I have the returned object stored in an array for each record returned and know how to traverse the JSON to access the right property/value in JS, however, I'm struggling to do the same within my ReactJS component. I'm still relatively new to React and can't seem to figure out the proper way traverse and display JSON properties and arrays. With my current setup I get Error: Objects are not valid as a React child (found: object with keys {recordDateSlugEdit, ... If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Any help would be greatly appreciated.

Returned JSON Blob:

[
  {
    "recordDateSlugEdit": "2017-08-17",
    "recordId": 119,
    "title": "POS Core Campaign CPL Rose 40%",
    "created_at": "2017-09-01T11:57:28.561Z",
    "updated_at": "2017-09-01T11:57:45.798Z",
    "user_id": 237,
    "category_id": 81,
    "app_user": {
      "userIdHash": "",
      "fullNameSlug": "Steve Matthews",
      "firstName": "Steve",
      "lastName": "Matthews"
    },
    "category": {
      "categoryIdHash": "",
      "categoryName": "Organic"
    },
    "record_comments": [
      {
        "createdAtDateSlug": "9\/1\/2017 8:13 AM",
        "commentId": 11,
        "comment": "Donec sem sapien, scelerisque fermentum interdum at, imperdiet vel dolor. Pellentesque fringilla elit eget risus maximus, aliquet luctus odio luctus. Sed pretium",
        "recordId": 119,
        "userId": 236,
        "created_at": "2017-09-01T12:13:23.557Z",
        "updated_at": "2017-09-01T12:13:23.557Z",
        "record_id": 119,
        "user_id": 236,
        "app_user": {
          "userIdHash": "oqX1p3EO5b",
          "fullNameSlug": "Brad Feld",
          "userId": 236,
          "firstName": "Brad",
          "lastName": "Feld",
        }
      }
    ]
  },
  {
    "recordDateSlugEdit": "2017-08-08",
    "recordId": 118,
    "title": "Added New CTA to Pricing Page",
    "user_id": 236,
    "category_id": 82,
    "app_user": {
      "userIdHash": "",
      "fullNameSlug": "Brad Feld",
      "firstName": "Brad",
      "lastName": "Feld",
    },
    "category": {
      "categoryIdHash": "",
      "categoryName": "Website"
    },
    "record_comments": [

    ]
  }
]

where I'm looking to access the properties found on the objects within the record_comments array located within each JSON record.

Here is my component setup:

import React from 'react';
import fetch from 'node-fetch';


//Comment Form
class CommentForm extends React.Component{
    render() {
        return (
            <form action="/app/record/comment" method="post">
            </form>
        )
    }
};

//Comments List
class Comments extends React.Component{

    constructor(props, context) {
        super(props, context);
        this.state = this.context.data || window.__INITIAL_STATE__ || {records: []};
    }

    fetchList() {
        fetch('http://localhost:3000/api/test')
            .then(res => {
                return res.json();
            })  
            .then(data => {
                let records = data.map((record) => {
                    return(
                        <div key={record.record_comments.commentId}>
                            <li>{record.record_comments.comment}</li>
                        </div>
                    )
                })
                this.setState({ records: data });
            })  
            .catch(err => {
                console.log(err);
            });
    }

    componentDidMount() {
        this.fetchList();
    }

    render() {
        return (
            <div>
            <h2>Comments List</h2>
            <ul>
                {this.state.records}
            </ul>
            </div>
        )
    }
};

//Comment Container
export default class CommentBox extends React.Component {

    render() {
        return (
            <div className="record-comment-form">
                <h1>Sweet it Worked</h1>
                <CommentForm />
                <hr />
                <Comments />
            </div>
        );
    }
}
2
  • 1
    Its just a typho i guess. Your setState inside fetchList should be this.setState({ records }); Commented Sep 26, 2017 at 10:57
  • Also one should not generate the JSX in fetch. You should do it in render. Commented Sep 26, 2017 at 10:57

2 Answers 2

0

The only element that may be a child of <ul> is <li>.In your case you are using div. Also You need to change
setState({records:data}) to setState({records}) or setState({records:records})

fetchList() {
    fetch('http://localhost:3000/api/test')
        .then(res => {
            return res.json();
        })  
        .then(data => {
            let records = data.map((record) => {
                return(

                        <li key={record.record_comments.commentId}>{record.record_comments.comment}</li>

                )
            })
            this.setState({ records:records});

        })  
        .catch(err => {
            console.log(err);
        });
}
Sign up to request clarification or add additional context in comments.

1 Comment

The error is not because of this though, it is mainly because of state
0

It seems that in

this.setState({ records: data });

data - is not a valid dom element. Try to replace it with

this.setState({ records });

since records - seems to be an array of jsx elements.

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.