1

I'm trying to create a component that will make an API call to get data about DJs, and use them to construct ReactStrap cards, and return these cards in a parent div flexbox.

At first, I thought of a ton of different ways to do this, but the method I've decided to do (and I'm not sure if this is how it's supposed to be done) is to store the data for each card as an array in my component's state.

I'll use the data later to construct cards using a map function on the array, and storing these components in a variable, which will be returned within another flexbox div.

import React from 'react'
import DjCard from "./DjCard"


class CreateDjCards extends React.Component {
  constructor() {
    super()
    this.state = {
      data: []
    }
  }

  componentDidMount() {
    fetch("URL")
      .then(JSON.stringify)
      .then(JSON.parse)
      .then((response) => this.setState({
        data: response.items
      }))
  }

  render() {
    let styles = {
      display: "flex",
      flexWrap: "wrap"
    }

    let cards = this.state.data.map( (item) => {
      return <DjCard data={item}/>
    })

    return(
      <div style={styles}>
        {cards}
      </div>
    )
  }
}

export default CreateDjCards

When I do this, it compiles successfully, but I get an error of "TypeError: Cannot read property 'map' of undefined". I expected a flexbox containing cards of every item described in the JSON.

What is the typical way of constructing numerous components from API data and returning them all/What am I doing incorrectly? Thanks!

2 Answers 2

1

Overall your setup for rendering the DjCard components is pretty reasonable I think, are you sure you're getting an array back from the API? Or is response.items what you think it is? Maybe items is undefined?

As a side note, check out https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch to see how you can clean up your .then chain on your fetch call--you don't need to stringify and parse the response :)

Sign up to request clarification or add additional context in comments.

1 Comment

Ok cool thanks, I figured out that yes for some reason I was not getting back the items I thought I was. I rewrote my fetch request using your link and my component worked.
1

Hi yes it seems that response.items is null, try logging the output of response and then set it correctly, mostly it would be response.data.items but still check after logging.

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.