I'm displaying a list of Todos
using React. Each Todo has a category
attribute displayed as a select
element, with a value
as the todo.category
. The select contains a list of option
mapped to each category available. When I delete a Todo that has a category
set, the next Todo displays that category, even though the Todo object itself does not have a category set. If I reload the page, the select
switches to the default value, as should have from the beginning. Here's my implementation:
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import actions from "../actions";
import categoriesSelector from "../reducers/categories/selectors";
const Todo = ({ todo, index }) => {
const dispatch = useDispatch();
const categories = useSelector(categoriesSelector.getCategories);
const handleDeleteTodo = () => {
dispatch(actions.deleteTodo(todo.id));
};
const handleAssignCategory = (e) => {
const categorizedTodo = { ...todo, category: e.target.value };
dispatch(actions.updateTodo(index, categorizedTodo));
};
return (
<li>
<label>{todo.title}</label>
{Array.isArray(categories) && (
<select onChange={handleAssignCategory} value={todo.category}>
<option value="No category">No category</option>
{categories.map(({ category }, index) => (
<option value={category} key={index}>
{category}
</option>
))}
</select>
)}
<button onClick={handleDeleteTodo}>Delete</button>
</li>
);
};
export default Todo;
Screenshots
List of todos, first todo has category cate1
Todos:
[
{
done: false,
title: 'todo1',
id: 70,
category: 'cate1'
},
{
done: false,
title: 'todo2',
id: 71
},
{
done: false,
title: 'todo3',
id: 72
}
],
Todos
:
[
{
done: false,
title: 'todo2',
id: 71
},
{
done: false,
title: 'todo3',
id: 72
}
],
How to correctly display the "No category" value?
CodePudding user response:
From my understanding you should try to store the todos array in a useState
and pass it in useEffect
hook for it to refresh on its on. That should render your page once you delete or add any todo and the old info won't come up. for example,
const [todo, setTodo] = useState([{ done: false, title: 'todo2', id: 71}]);
useEffect(() => {
}, [todo])
CodePudding user response:
<button onClick={(id)=>handleDeleteTodo(id)}>Delete</button>
const handleDeleteTodo = (id) => {
dispatch(actions.deleteTodo(id));
};
you send spasefic id and delete to do list item