Cat Perry
Cat Perry

Reputation: 1052

Fetch request in React: How do I Map through JSON array of objects, setState() & append?

This API returns a JSON array of objects, but I'm having trouble with setState and appending. Most documentation covers JSON objects with keys. The error I get from my renderItems() func is: ItemsList.js:76 Uncaught TypeError: Cannot read property 'map' of undefined

in ItemsList.js

import React, { Component } from "react";
import NewSingleItem from './NewSingleItem';
import { findDOMNode } from 'react-dom';

const title_URL = "https://www.healthcare.gov/api/index.json";

class ItemsList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // error: null,
      // isLoaded: false,
      title: [],
      url: [],
      descrip: []
    };
  }

  componentDidMount() {
    fetch(title_URL)
      .then(response => {
        return response.json();
      })
      .then((data) => {
        for (let i = 0; i < data.length; i++) {
          this.setState({
            title: data[i].title,
            url: data[i].url,
            descrip: data[i].bite,
          });
          console.log(data[i])   
        }

      })
      .catch(error => console.log(error));
  }

  renderItems() {
    return this.state.title.map(item => {
      <NewSingleItem key={item.title} item={item.title} />;
    });
  }

  render() {
    return <ul>{this.renderItems()}</ul>;
  }
}

export default ItemsList;

Above, I'm trying to map through the items, but I'm not quite sure why I cant map through the objects I set in setState(). Note: even if in my setState() I use title: data.title, it doesnt work. Can someone explain where I'm erroring out? Thanks.

in App.js

import React, { Component } from "react";
import { hot } from "react-hot-loader";
import "./App.css";
import ItemsList from './ItemsList';

class App extends Component {
  render() {
    return (
      <div className="App">
        <h1> Hello Healthcare </h1>
        <ItemsList />
        <article className="main"></article>
      </div>
    );
  }
}

export default App;

in NewSingleItem.js

import React, { Component } from "react";

const NewSingleItem = ({item}) => {
  <li>
    <p>{item.title}</p>
  </li>
};

export default NewSingleItem;

Upvotes: 3

Views: 17520

Answers (1)

Blue
Blue

Reputation: 22911

The problem is this line:

this.setState({
  title: data[i].title,
  url: data[i].url,
  descrip: data[i].bite,
});

When you state this.state.title to data[i].title, it's no longer an array. You need to ensure it stays an array. You probably don't want to split them up anyway, just keep them all in a self contained array:

this.state = {
  // error: null,
  // isLoaded: false,
  items: [],
};

...


componentDidMount() {
  fetch(title_URL)
    .then(response => {
      return response.json();
    })
    .then((data) => {
      this.setState({
        items: data.map(item => ({
            title: item.title,
            url: item.url,
            descrip: item.bite,
        })
      });
      console.log(data[i])   
    }
  })

...

renderItems() {
  return this.state.items.map(item => {
    <NewSingleItem key={item.title} item={item.title} />;
  });
}

Upvotes: 4

Related Questions