Updating Arrays in State·续2
button { margin: 5px; }
li { list-style-type: none; }
ul, li { margin: 0; padding: 0; }
In handleAddTodo, you can use the array spread syntax. In handleChangeTodo, you can create a new array with map. In handleDeleteTodo, you can create a new array with filter. Now the list works correctly:
```js src/App.js import { useState } from 'react'; import AddTodo from './AddTodo.js'; import TaskList from './TaskList.js';
let nextId = 3; const initialTodos = [ { id: 0, title: 'Buy milk', done: true }, { id: 1, title: 'Eat tacos', done: false }, { id: 2, title: 'Brew tea', done: false }, ];
export default function TaskApp() { const [todos, setTodos] = useState( initialTodos );
function handleAddTodo(title) { setTodos([ ...todos, { id: nextId++, title: title, done: false } ]); }
function handleChangeTodo(nextTodo) { setTodos(todos.map(t => { if (t.id === nextTodo.id) { return nextTodo; } else { return t; } })); }
function handleDeleteTodo(todoId) { setTodos( todos.filter(t => t.id !== todoId) ); }
return (
<>
```js src/AddTodo.js
import { useState } from 'react';
export default function AddTodo({ onAddTodo }) {
const [title, setTitle] = useState('');
return (
<>
<input
placeholder="Add todo"
value={title}
onChange={e => setTitle(e.target.value)}
/>
<button onClick={() => {
setTitle('');
onAddTodo(title);
}}>Add</button>
</>
)
}
```js src/TaskList.js import { useState } from 'react';
export default function TaskList({ todos, onChangeTodo, onDeleteTodo }) { return (
-
{todos.map(todo => (
-
function Task({ todo, onChange, onDelete }) { const [isEditing, setIsEditing] = useState(false); let todoContent; if (isEditing) { todoContent = ( <> { onChange({ ...todo, title: e.target.value }); }} /> </> ); } else { todoContent = ( <> {todo.title} </> ); } return ( ); }
```css
button { margin: 5px; }
li { list-style-type: none; }
ul, li { margin: 0; padding: 0; }
Fix the mutations using Immer
This is the same example as in the previous challenge. This time, fix the mutations by using Immer. For your convenience, useImmer is already imported, so you need to change the todos state variable to use it.
```js src/App.js import { useState } from 'react'; import { useImmer } from 'use-immer'; import AddTodo from './AddTodo.js'; import TaskList from './TaskList.js';
let nextId = 3; const initialTodos = [ { id: 0, title: 'Buy milk', done: true }, { id: 1, title: 'Eat tacos', done: false }, { id: 2, title: 'Brew tea', done: false }, ];
export default function TaskApp() { const [todos, setTodos] = useState( initialTodos );
function handleAddTodo(title) { todos.push({ id: nextId++, title: title, done: false }); }
function handleChangeTodo(nextTodo) { const todo = todos.find(t => t.id === nextTodo.id ); todo.title = nextTodo.title; todo.done = nextTodo.done; }
function handleDeleteTodo(todoId) { const index = todos.findIndex(t => t.id === todoId ); todos.splice(index, 1); }
return (
<>
```js src/AddTodo.js
import { useState } from 'react';
export default function AddTodo({ onAddTodo }) {
const [title, setTitle] = useState('');
return (
<>
<input
placeholder="Add todo"
value={title}
onChange={e => setTitle(e.target.value)}
/>
<button onClick={() => {
setTitle('');
onAddTodo(title);
}}>Add</button>
</>
)
}
```js src/TaskList.js import { useState } from 'react';
export default function TaskList({ todos, onChangeTodo, onDeleteTodo }) { return (
-
{todos.map(todo => (
-
function Task({ todo, onChange, onDelete }) { const [isEditing, setIsEditing] = useState(false); let todoContent; if (isEditing) { todoContent = ( <> { onChange({ ...todo, title: e.target.value }); }} /> </> ); } else { todoContent = ( <> {todo.title} </> ); } return ( ); }
```css
button { margin: 5px; }
li { list-style-type: none; }
ul, li { margin: 0; padding: 0; }
```json package.json { "dependencies": { "immer": "1.7.3", "react": "latest", "react-dom": "latest", "react-scripts": "latest", "use-immer": "0.5.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }
With Immer, you can write code in the mutative fashion, as long as you're only mutating parts of the `draft` that Immer gives you. Here, all mutations are performed on the `draft` so the code works:
```js src/App.js
import { useState } from 'react';
import { useImmer } from 'use-immer';
import AddTodo from './AddTodo.js';
import TaskList from './TaskList.js';
let nextId = 3;
const initialTodos = [
{ id: 0, title: 'Buy milk', done: true },
{ id: 1, title: 'Eat tacos', done: false },
{ id: 2, title: 'Brew tea', done: false },
];
export default function TaskApp() {
const [todos, updateTodos] = useImmer(
initialTodos
);
function handleAddTodo(title) {
updateTodos(draft => {
draft.push({
id: nextId++,
title: title,
done: false
});
});
}
function handleChangeTodo(nextTodo) {
updateTodos(draft => {
const todo = draft.find(t =>
t.id === nextTodo.id
);
todo.title = nextTodo.title;
todo.done = nextTodo.done;
});
}
function handleDeleteTodo(todoId) {
updateTodos(draft => {
const index = draft.findIndex(t =>
t.id === todoId
);
draft.splice(index, 1);
});
}
return (
<>
<AddTodo
onAddTodo={handleAddTodo}
/>
<TaskList
todos={todos}
onChangeTodo={handleChangeTodo}
onDeleteTodo={handleDeleteTodo}
/>
</>
);
}
```js src/AddTodo.js import { useState } from 'react';
export default function AddTodo({ onAddTodo }) { const [title, setTitle] = useState(''); return ( <> setTitle(e.target.value)} /> </> ) }
```js src/TaskList.js
import { useState } from 'react';
export default function TaskList({
todos,
onChangeTodo,
onDeleteTodo
}) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
<Task
todo={todo}
onChange={onChangeTodo}
onDelete={onDeleteTodo}
/>
</li>
))}
</ul>
);
}
function Task({ todo, onChange, onDelete }) {
const [isEditing, setIsEditing] = useState(false);
let todoContent;
if (isEditing) {
todoContent = (
<>
<input
value={todo.title}
onChange={e => {
onChange({
...todo,
title: e.target.value
});
}} />
<button onClick={() => setIsEditing(false)}>
Save
</button>
</>
);
} else {
todoContent = (
<>
{todo.title}
<button onClick={() => setIsEditing(true)}>
Edit
</button>
</>
);
}
return (
<label>
<input
type="checkbox"
checked={todo.done}
onChange={e => {
onChange({
...todo,
done: e.target.checked
});
}}
/>
{todoContent}
<button onClick={() => onDelete(todo.id)}>
Delete
</button>
</label>
);
}
button { margin: 5px; }
li { list-style-type: none; }
ul, li { margin: 0; padding: 0; }
```json package.json { "dependencies": { "immer": "1.7.3", "react": "latest", "react-dom": "latest", "react-scripts": "latest", "use-immer": "0.5.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }
You can also mix and match the mutative and non-mutative approaches with Immer.
For example, in this version `handleAddTodo` is implemented by mutating the Immer `draft`, while `handleChangeTodo` and `handleDeleteTodo` use the non-mutative `map` and `filter` methods:
```js src/App.js
import { useState } from 'react';
import { useImmer } from 'use-immer';
import AddTodo from './AddTodo.js';
import TaskList from './TaskList.js';
let nextId = 3;
const initialTodos = [
{ id: 0, title: 'Buy milk', done: true },
{ id: 1, title: 'Eat tacos', done: false },
{ id: 2, title: 'Brew tea', done: false },
];
export default function TaskApp() {
const [todos, updateTodos] = useImmer(
initialTodos
);
function handleAddTodo(title) {
updateTodos(draft => {
draft.push({
id: nextId++,
title: title,
done: false
});
});
}
function handleChangeTodo(nextTodo) {
updateTodos(todos.map(todo => {
if (todo.id === nextTodo.id) {
return nextTodo;
} else {
return todo;
}
}));
}
function handleDeleteTodo(todoId) {
updateTodos(
todos.filter(t => t.id !== todoId)
);
}
return (
<>
<AddTodo
onAddTodo={handleAddTodo}
/>
<TaskList
todos={todos}
onChangeTodo={handleChangeTodo}
onDeleteTodo={handleDeleteTodo}
/>
</>
);
}
```js src/AddTodo.js import { useState } from 'react';
export default function AddTodo({ onAddTodo }) { const [title, setTitle] = useState(''); return ( <> setTitle(e.target.value)} /> </> ) }
```js src/TaskList.js
import { useState } from 'react';
export default function TaskList({
todos,
onChangeTodo,
onDeleteTodo
}) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
<Task
todo={todo}
onChange={onChangeTodo}
onDelete={onDeleteTodo}
/>
</li>
))}
</ul>
);
}
function Task({ todo, onChange, onDelete }) {
const [isEditing, setIsEditing] = useState(false);
let todoContent;
if (isEditing) {
todoContent = (
<>
<input
value={todo.title}
onChange={e => {
onChange({
...todo,
title: e.target.value
});
}} />
<button onClick={() => setIsEditing(false)}>
Save
</button>
</>
);
} else {
todoContent = (
<>
{todo.title}
<button onClick={() => setIsEditing(true)}>
Edit
</button>
</>
);
}
return (
<label>
<input
type="checkbox"
checked={todo.done}
onChange={e => {
onChange({
...todo,
done: e.target.checked
});
}}
/>
{todoContent}
<button onClick={() => onDelete(todo.id)}>
Delete
</button>
</label>
);
}
button { margin: 5px; }
li { list-style-type: none; }
ul, li { margin: 0; padding: 0; }
json package.json
{
"dependencies": {
"immer": "1.7.3",
"react": "latest",
"react-dom": "latest",
"react-scripts": "latest",
"use-immer": "0.5.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
With Immer, you can pick the style that feels the most natural for each separate case.
