So I am following a tutorial for building a react todo list with a rails api.
When I try to add a task to the list it renders the bullet point but not the text. Checking the console its tells me the error is:
"Warning: Each child in a list should have a unique "key" prop.
But I'm pretty sure I assigned a key prop already?
I checked the line of code in question the
{this.state.items.map((item) => (<TodoItem key={item.id} item={item} >{item}</TodoItem>
and it appears to be correct So I'm not sure what I'm doing wrong here?
This is my TodoList.js
import React, { Component } from "react";
import TodoForm from "./TodoForm";
import TodoItem from "./TodoItem";
const api_url = "http://localhost:3001/api/v1/todos"
class TodoList extends Component {
constructor(props) {
super(props)
this.state = {
items: []
}
this.updateTodoList = this.updateTodoList.bind(this);
}
componentDidMount () {
this.getTasks();
}
getTasks() {
fetch(api_url)
.then(response => response.json())
.then(response_items => {
this.setState({
items: response_items.reverse()
})
});
}
updateTodoList(item) {
let _items = this.state.items
// unshift adds to beginning of array
_items.unshift(item)
this.setState({
items: _items
})
}
render() {
console.log(this.state.items)
return (
<div>
<TodoForm api_url={api_url} updateTodoList={this.updateTodoList} />
<ul id="todo_list">
{this.state.items.map((item) => (
<TodoItem key={item.id} item={item} >{item}</TodoItem>
))}
</ul>
</div>
)
}
}
export default TodoList;
This is my ToDoItem.js
import React from "react";
export default function TodoItem(props) {
return (
<li>{props.item.task}</li>
)
}
Any help on understanding and fixing this error would be appreciated.
CodePudding user response:
Your item.id
isn't unique. Try to console.log
your item.id
to check if they are unique.
Or try:
{this.state.items.map((item, index) => (
<TodoItem key={index} item={item}>{item}</TodoItem>
))}
CodePudding user response:
I fixed the error I was missing a parenthesis set in my FormSubmit function so
async formSubmit(formData) {
var data = new FormData(formData)
await fetch(this.state.api_url, {
method: "POST",
mode: "cors",
body: data
}).then(response => response.json)
.then(response => this.props.updateTodoList(response))
}
became
async formSubmit(formData) {
var data = new FormData(formData)
await fetch(this.state.api_url, {
method: "POST",
mode: "cors",
body: data
}).then(response => response.json())
.then(response => this.props.updateTodoList(response))
}
and that fixed it