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!