-
Notifications
You must be signed in to change notification settings - Fork 12.6k
Expand file tree
/
Copy pathtodos-context.tsx
More file actions
49 lines (38 loc) · 1.16 KB
/
todos-context.tsx
File metadata and controls
49 lines (38 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React, { useState } from 'react';
import Todo from '../models/todo';
type TodosContextObj = {
items: Todo[];
addTodo: (text: string) => void;
removeTodo: (id: string) => void;
};
export const TodosContext = React.createContext<TodosContextObj>({
items: [],
addTodo: () => {},
removeTodo: (id: string) => {},
});
// In React 18.x you have to include the children prop yourself, I wrote solution below
const TodosContextProvider: React.FC<{ children: JSX.Element | JSX.Element[] }> = (props) => {
const [todos, setTodos] = useState<Todo[]>([]);
const addTodoHandler = (todoText: string) => {
const newTodo = new Todo(todoText);
setTodos((prevTodos) => {
return prevTodos.concat(newTodo);
});
};
const removeTodoHandler = (todoId: string) => {
setTodos((prevTodos) => {
return prevTodos.filter((todo) => todo.id !== todoId);
});
};
const contextValue: TodosContextObj = {
items: todos,
addTodo: addTodoHandler,
removeTodo: removeTodoHandler,
};
return (
<TodosContext.Provider value={contextValue}>
{props.children}
</TodosContext.Provider>
);
};
export default TodosContextProvider;