Skip to content

Instantly share code, notes, and snippets.

@shawnshuang
Last active January 14, 2022 21:57
Show Gist options
  • Save shawnshuang/1c032a51a6cec4b6002e872c2c956a14 to your computer and use it in GitHub Desktop.
Save shawnshuang/1c032a51a6cec4b6002e872c2c956a14 to your computer and use it in GitHub Desktop.
// 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/>
</>
</>
// 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