Skip to content

Instantly share code, notes, and snippets.

@malerba118
Last active February 17, 2019 05:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malerba118/d412832a11d977e0a694aebe8cd8aaaa to your computer and use it in GitHub Desktop.
Save malerba118/d412832a11d977e0a694aebe8cd8aaaa to your computer and use it in GitHub Desktop.
Optimistic Updates
const useNormalizedApi = () => {
let db = useDB();
return {
...
updateTodo: async (id, payload, oldTodo) => {
// Let's assume the update will be successful
let normalizedTodoData = normalize(payload, TodoSchema);
db.mergeEntities(normalizedTodoData.entities);
try {
let todo = await api.updateTodo(id, payload);
// If successful, let's update again to make sure we have the latest todo data
normalizedTodoData = normalize(todo, apiSchemas.updateTodoResponseSchema);
db.mergeEntities(normalizedTodoData.entities);
}
catch(e) {
// If update fails, let's normalize the old todo and merge it back into the db
normalizedTodoData = normalize(oldTodo, TodoSchema);
db.mergeEntities(normalizedTodoData.entities);
}
},
...
};
};
const TodosComponent = (props) => {
let db = useDB();
let allTodosQuery = db.getStoredQuery('ALL_TODOS');
let todos = db.executeQuery(allTodosQuery);
return (
<JSON data={todos} />
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment