0

I have an issue with this code: TypeError: Cannot read property 'map' of undefined

Please guide me on what to do

app.js

import React from "react";

import {CardList} from "./componets/card-list/card-list";


class App extends React.Component {
    constructor() {
        super();
        this.state={
            monsters:
                []
        };
    }
    componentDidMount() {
        fetch('http://jsonplaceholder.typicode.com/users')
            .then(res => res.json())
            .then((data) => {
                this.setState({ monsters: data })
            })
    }
    render() {
     return(
         <div>
             <CardList monters={this.state.monsters}/>
         </div>
     )
 }
}
export default App;

and cardlist.jsx Please guide me on what to do

import './card-list.css'


export const CardList=(props) => (

     <div className='card-list'>{props.monsters.map(monster =>(<h1 key={monster.id}>{monster.name}</h1>))}

    </div>
);```


1
  • monters !== monsters. Commented Apr 1, 2020 at 10:23

2 Answers 2

3

You missed here:

<CardList monters={this.state.monsters}/>

You called your prop monters

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

Comments

0

You need to set the default value of data to empty array incase you receive nothing from the fetch request. Try following:

import React from "react";

import {CardList} from "./componets/card-list/card-list";


class App extends React.Component {
    constructor() {
        super();
        this.state={
            monsters:
                []
        };
    }
    componentDidMount() {
        fetch('http://jsonplaceholder.typicode.com/users')
            .then(res => res.json())
            .then((data = []) => {
                this.setState({ monsters: data })
            })
    }
    render() {
     return(
         <div>
             <CardList monters={this.state.monsters}/>
         </div>
     )
 }
}
export default App;

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.