Created
September 30, 2022 06:18
-
-
Save jonwhittlestone/b39c59e7485e828f47b3514c20154dae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
import Todo from "../models/todo"; | |
type TodosContextObj = { | |
items: Todo[]; | |
addTodo: (text: string) => void; | |
removeTodo: (id: string) => void; | |
}; | |
/** | |
* createCotext is a generic type so we | |
* can add angle brackets to better describe the context obj. | |
* Such as the type of values that will end up in `items[]` array | |
*/ | |
export const TodosContext = React.createContext<TodosContextObj>({ | |
// These are concrete implementations | |
items: [], | |
addTodo: () => {}, | |
removeTodo: (id: string) => {}, | |
}); | |
// type Props = { | |
// children: React.ReactNode; | |
// }; | |
// const TodosContextProvider: React.FC<PropsWithChildren> = ({ children }) => { | |
// // return <TodosContext.Provider>{props.children}</TodosContext.Provider>; | |
// return <TodosContext.Provider>{children}</TodosContext.Provider>; | |
// }; | |
const TodosContextProvider: React.FC = (props) => { | |
// return <TodosContext.Provider>{props.children}</TodosContext.Provider>; | |
// return <TodosContext.Provider>{children}</TodosContext.Provider>; | |
// useState(); | |
// const todos = [new Todo("Learn React"), new Todo("Learn TypeScript")]; | |
// Defining the state: useState is a generic function, so | |
// in order to tell it what type of | |
// data to expect, specify "array of Todo models" within the | |
// curly brakcets. | |
const [todos, setTodos] = useState<Todo[]>([]); | |
const addTodoHandler = (text: string) => { | |
const newTodo = new Todo(text); | |
// properly update the state based on the previous state | |
setTodos((prevTodos) => { | |
return prevTodos.concat(newTodo); | |
}); | |
}; | |
/** | |
* This is the actual implementation. | |
* Add the param first here, then fix compiler errors. | |
* @param todoId | |
* @returns | |
*/ | |
const removeTodoHandler = (todoId: string) => { | |
// Param below ⬇️ Updating the state, based on the previous state | |
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment