-
-
Save nhunzaker/81aa65a6a7b496a2e6ca to your computer and use it in GitHub Desktop.
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
let users = [] | |
// This could be our action, a generator | |
let createUser = function* (params) { | |
// This is an optimistic update | |
yield { id: 'cid0', ...params } | |
// This simulates some async behavior to go do something | |
yield Promise.resolve({ id: 0, name: params.name }) | |
} | |
// This could be our store. It is a pure function | |
let addUser = function (users, params) { | |
return users.concat(params) | |
} | |
function dispatch(state, params) { | |
console.log(addUser(state, params)) | |
} | |
function push(params) { | |
// The same state is sent to all `yields`, so | |
// optimistic updates will be blown away by later calls | |
let state = users | |
for (let body of createUser({ name: 'Bob' })) { | |
if (typeof body.then === 'function') { | |
body.then(result => dispatch(state, result)) | |
} else { | |
dispatch(state, body) | |
} | |
} | |
} | |
push({ name: 'bob' }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment