afi
afi

Reputation: 603

react js is getting Cannot read property 'map' of undefined

i am beginner in reactjs. i am getting map error in higher order component. when i try to console.log(items) the items is showing in console log but items are not rendering in template can anybody tell me how can i solve the error TypeError: Cannot read property 'map' of undefined

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            items: []
        };
    }

    componentDidMount() {
        fetch("https://jsonplaceholder.typicode.com/todos/")
            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        items: result.items
                    });
                }
            )
    }

    render() {
        const { items } = this.state;

        return (
            <ul>
                {items.map(item => (
                    <li key={item.id}>
                        {item.name} {item.price}
                    </li>
                ))}
            </ul>
        );

    }
}
const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement)

Upvotes: 0

Views: 41

Answers (3)

CertainPerformance
CertainPerformance

Reputation: 371138

Look at the payload of the endpoint. It looks like:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  // ...

The result argument is a plain array; it's not an object with an items property. Use:

this.setState({
  items: result
});

The items don't have price properties either. Choose either userId, id, title, or completed.

Upvotes: 2

ljbc1994
ljbc1994

Reputation: 2254

The response from https://jsonplaceholder.typicode.com/todos/ returns an array already so you just need to make the following change:


    componentDidMount() {
        fetch("https://jsonplaceholder.typicode.com/todos/")
            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        items: result // just return result               
                    });
                }
            )
    }

Upvotes: 1

claud.io
claud.io

Reputation: 1963

i'm pretty sure that in this code:

 this.setState({ items: result.items});

result.items is not an array or what you expect, i suggest to log the result and check that is an array

Upvotes: 1

Related Questions