Skip to content

Instantly share code, notes, and snippets.

@Georgegriff
Created January 10, 2022 10:41
Show Gist options
  • Select an option

  • Save Georgegriff/96b4948ca205f6587ea379e6b6f74fa7 to your computer and use it in GitHub Desktop.

Select an option

Save Georgegriff/96b4948ca205f6587ea379e6b6f74fa7 to your computer and use it in GitHub Desktop.
hooks mutations - saving
<TodoContext.Provider
value={{
save: () => {
// contrived code for the demonstration
// in the real app this was responsible for deciding if a request should be sent to server or not
const existingTodoKeys = Array.from(existingTodos().keys());
const draftTodoKeys = Array.from(draftTodos.keys());
let todosHasChanges = existingTodoKeys.length !== draftTodoKeys.length;
// now check entries using ids, unless we know they have changed based on length
// there are better ways of detecting changes but this demonstrates the issue
if (!todosHasChanges) {
const existingTodoValues = Array.from(existingTodos().values());
const draftTodoValues = Array.from(draftTodos.values());
for (let todoIndex = 0; todoIndex < draftTodoKeys.length; todoIndex++) {
// now check each entry
if (
existingTodoKeys[todoIndex] !== draftTodoKeys[todoIndex] ||
existingTodoValues[todoIndex].done !==
draftTodoValues[todoIndex].done
) {
todosHasChanges = true;
break;
}
}
}
if (todosHasChanges) {
// send off request to server
}
},
}}
>
{children}
</TodoContext.Provider>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment