Last active
July 23, 2019 09:44
-
-
Save hosembafer/cd368c87ecfcb72114f7deadb324ab55 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, useCallback } from 'react'; | |
const Context = React.createContext(); | |
let nextId = 0; | |
export const TodoListProvider = ({children}) => { | |
const [tasks, setTasks] = useState([]); | |
const addTask = useCallback(name => setTasks(tasks => ([...tasks, {id: ++nextId, name}])), [setTasks]); | |
const renameTask = useCallback((id, name) => setTasks(tasks => tasks.map(task => ({...task, name: id === task.id ? name : task.name}))), [setTasks]); | |
const removeTask = useCallback(id => setTasks(tasks => tasks.filter((task) => id !== task.id)), [setTasks]); | |
const value = { tasks, addTask, renameTask, removeTask }; | |
return ( | |
<Context.Provider value={value}> | |
{children} | |
</Context.Provider> | |
); | |
}; | |
export const useTodoListStore = () => React.useContext(Context); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment