Aessandro
Aessandro

Reputation: 5761

React iterate over object from json data

I have the following code:

import ReactDom from 'react-dom';
import React from 'react';
import {render} from 'react-dom';
import $ from 'jquery';

class News extends React.Component {
  render () {
    var news = [];
    this.props.news.forEach(function(el, i){
        news.push(<SingleNews key={i} img={el.img} />);
    });
    return (
      <section className="news-wrapper">
          {news}
      </section>
    );
  }
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          data: ''
        }
    }
    mapObject(object, callback) {
      return Object.keys(object).map(function (key) {
        return callback(key, object[key]);
      });
    }
    componentDidMount () {
      const newsfeedURL = 'https://s3-eu-west-1.amazonaws.com/streetlife-coding-challenge/newsfeed.json';
      $.get(newsfeedURL, function(result) {
        this.setState({data: JSON.parse(result)});
        console.log(typeof this.state.data.messages);
      }.bind(this));
    }
    render () {
        return (
            <div>
                {Object.keys(this.state.data.messages).map(function(key) {
                    return <div>Key: {key}, Value: {this.state.data.messages[key]}</div>;
                })}
            </div>
        )
    }
}


ReactDom.render(
  <App />,
  document.getElementById('app')
);

I am trying ti iterate over "this.state.data.messages" to output some data inside the render method.

After typing this "console.log(typeof this.state.data.messages);" I have gathered that "this.state.data.messages" is an object hence the following:

            {Object.keys(this.state.data.messages).map(function(key) {
                return <div>Key: {key}, Value: {this.state.data.messages[key]}</div>;
            })}

however I have the following inside my console:

Uncaught TypeError: Cannot convert undefined or null to object

Upvotes: 2

Views: 7880

Answers (2)

finalfreq
finalfreq

Reputation: 6980

The problem here is you are initially setting data as an empty string. In your componentDidMount you are making the ajax call and since it's async react will still render. Once it renders it's trying to access this.state.data.messages which this.state.data is an empty string so will have no property called messages.

What I would do is have an initial state property called loading and in your render method if this.state.loading === true render something else in the div and if this.state.loading === false && this.state.data.messages actually return what your trying to do now.

Just make sure to set state of loading to false when you parse the JSON response

this.state = {
   data: '',
   loading: true
}
componentDidMount () {
    const newsfeedURL = 'https://s3-eu-west-1.amazonaws.com/streetlife-coding-challenge/newsfeed.json';
    $.get(newsfeedURL, function(result) {
        this.setState({
          data: JSON.parse(result),
          loading: false
        });
        console.log(typeof this.state.data.messages);
    }.bind(this));
}
render () {
  let content;
  if (this.state.loading === false && this.state.data.messages) {
    content = {Object.keys(this.state.data.messages).map(function(key) {
      return <div>Key: {key}, Value: {this.state.data.messages[key]}</div>;
    })}
  } else { 
    content = ''; // whatever you want it to be while waiting for data
  }
  return (
    <div>
      {content}
    </div>
  )
}

Upvotes: 5

Dave Newton
Dave Newton

Reputation: 160170

You're going to be rendering before that async call returns.

You need to handle the case before there's data. If nothing else you should change the initial state to better match the state you're expecting.

Upvotes: 3

Related Questions