Last active
February 17, 2019 05:00
-
-
Save malerba118/d412832a11d977e0a694aebe8cd8aaaa to your computer and use it in GitHub Desktop.
Optimistic Updates
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
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