Rachel Romée Rachel Romée - 3 months ago 9
React JSX Question

Map undefined in ReactJS code for todo list app

I just started coding in ReactJS and have to build a todo application. Now there is a problem when displaying to-do items received from an API call. This is the error I get:

Uncaught TypeError: Cannot read property 'map' of undefined

This is the code:

TodoList.js

import React from 'react';
import $ from 'jquery';
import TodoItem from './TodoItem';

class TodoList extends React.Component {
constructor() {
super();

this.state = {
todos: [
{id: 0, title: "", completed: false}
]
};
}


componentDidMount() {
this.loadTodos();
}

loadTodos(event) {
let component = this;

$.getJSON(`https://whispering-thicket-55256.herokuapp.com/todos.json`, function(data) {
console.log(data);

component.setState({
todos: data.todos
});
});
}

renderTodos(todo, i) {
return (
<TodoItem
key={todo.id}
id={todo.id}
title={todo.title}
completed={todo.completed}
createdAt={todo.created_at}
updatedAt={todo.updated_at} />
);
}

render() {
let todos = this.state.todos
return (
<div>
<ul>
{todos.map(this.renderTodos.bind(this))}
</ul>
</div>
);
}
}

export default TodoList;


TodoItem.js

import React from 'react';
import jQuery from 'jquery';

class TodoItem extends React.Component {
componentDidMount() {
this.setState({
id: this.props.id,
title: this.props.title,
completed: this.props.completed,
createdAt: this.props.createdAt,
updatedAt: this.props.updatedAt
})
}

render() {
console.log(this.props);
return (
<li>{this.props.title}</li>
);
}
}

export default TodoItem;


I can't see what I'm doing wrong here .. Hope someone can help me. What I want to achieve is to display all to-do items from the .json url in a list.
If you need more code (app.js?) then I'll post that too!

Thanks!

Answer

data.todos returns undefined

change this

component.setState({
     todos: data.todos
});

to

component.setState({
     todos: data
});

because derived data is array of todos allready

Comments