Last active
January 14, 2022 21:57
-
-
Save shawnshuang/1c032a51a6cec4b6002e872c2c956a14 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Components | |
function TaskDialog() { | |
... | |
const { addTask } = useTasks(); | |
... | |
} | |
function TaskItem() { | |
... | |
const { updateTask } = useTasks(); | |
... | |
} | |
function TaskList() { | |
... | |
const { reorderTasks } = useTasks(); | |
... | |
} | |
function TaskPage() { | |
... | |
const { | |
tasks, | |
deleteTask, | |
} = useTasks(); | |
... | |
} | |
// JSX | |
// This is to give an idea of the component hierarchy. I also know | |
// that this is not proper syntax, but it makes it easier to skim. | |
<TasksProvider> | |
<TaskPage> | |
<TaskList> | |
{tasks.map((task) => ( | |
<TaskItem | |
key={task.id} | |
task={task} | |
/> | |
))} | |
</> | |
<TaskDialog/> | |
</> | |
</> |
This file contains hidden or 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
// Provider | |
function TasksProvider() { | |
const [tasks, setTasks] = useState(); | |
useEffect(() => { | |
// Fetch tasks and save with setTasks(). | |
}); | |
return ( | |
<TasksContext.Provider | |
value={{ | |
tasks, | |
setTasks, | |
}} | |
> | |
{children} | |
</TasksContext.Provider> | |
); | |
} | |
// Hook | |
function useTasks() { | |
const context = useContext(TasksContext); | |
const { | |
tasks, | |
setTasks, | |
} = context; | |
// Each of the following functions essentially do the same thing: | |
// (1) Clone tasks. | |
// (2) Update list of cloned tasks accordingly. | |
// (3) Update client state. | |
// (4) Make API request to update server state. | |
const addTask = () => { ... } | |
const updateTask = () => { ... } | |
const reorderTasks = () => { ... } | |
const deleteTask = () => { ... } | |
return { | |
tasks, | |
addTask, | |
updateTask, | |
reorderTasks, | |
deleteTask, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment