Reputation: 91
1.I'm using React to make a TodoList. It works until you add a list, An error occurred when adding the delete feature when the button is clicked
2.Is it a problem to use use useContext to separate lists from other files?
I'm sorry for the awkwardness of the question. Thank you for your help in solving this problem.
import React, { useContext} from 'react';
import Todo from './Todo';
import { ListContext } from './ListContext';
const TodoList = () => {
const [lists, setLists] = useContext(ListContext);
return (
<div>
{lists.map((list, index) => {
return <Todo list={list.todos} key={index}/>
})}
</div>
);
}
export default TodoList;
import React, {useContext} from 'react';
import { ListContext } from './ListContext';
const Btn = (id) => {
const [lists, setLists] = useContext(ListContext);
const onRemove = (id) => {
setLists({
lists: lists.filter(list => list.id !== id)
});
}
return(
<>
<button onClick={(e) => {
e.stopPropagation();
onRemove(id);
}}>x</button>
</>
); `enter code here`
}
export default Btn;
import React, {useState, createContext,} from 'react';
export const ListContext = createContext();
export const ListProvider = (props) => {
const [lists, setLists] = useState([
{
todos: 'Make a TodoList',
id: 1,
},
]);
return(
<ListContext.Provider value={[lists, setLists]}>
{props.children}
</ListContext.Provider>
);
}
TypeError: lists.map is not a function TodoList C:/Users/user/Desktop/Work/VSC-workspace/React/todolist/src/component/TodoList.jsx:11 8 | const [lists, setLists] = useContext(ListContext); 9 | 10 | return (
11 | `enter code here | ^ 12 | {lists.map((list, index) => { 13 | return 14 | })}
Upvotes: 1
Views: 3541
Reputation: 20755
You problem is here, you are passing only todos
from lists
and not id
<Todo list={list.todos} key={index}/>
In Todo
component you are trying to access list.id
which is undefined
, because you have not passed it from TodoList
component.
In TodoList
component, instead of passing list.todos
you need to pass list
only like,
<Todo list={list} key={index}/>
Your Todo
component should be,
const Todo = ({list}) => {
return(
<div className="todolist">
<li>
{list.todos}
<Btn id={list.id}/>
</li>
</div>
);
}
Also another problem is in Btn
component definition,
const Btn = (id) => { ...
you need to do this,
const Btn = ({id}) => { ... //notice the curly braces as you did in `Todo` component
Note: Still you face any issue here
lists.filter(list => list.id !== id)
You can do this,
lists.filter(list => Number(list.id) !== Number(id)) //possibility that `id` props might come as `string` type
Upvotes: 1