Skip to content

Commit

Permalink
Feature: Allow update to take a reducer.
Browse files Browse the repository at this point in the history
A reducer is a function that takes the state and returns a new state
or a reducer.

  update(state => {
    return { value: state.value + 1 }
  }

This allows you to get the current & latest state inside the
callback of some async call.

The alternative is using the state that was passed to the
action that originated the async call. The problem is that
this reference to the state may have gone out-of-date if
other actions run and finished during the async process
and changed the state.
  • Loading branch information
Jorge Bucaran committed Aug 31, 2017
1 parent fbd25db commit 2b35ff2
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ export function app(props) {
if (typeof action === "function") {
actions[key] = function(data) {
emit("action", { name: name, data: data })
return update(emit("resolve", action(appState, appActions, data)))

var result = emit("resolve", action(appState, appActions, data))

return typeof result === "function" ? result(update) : update(result)
}
} else {
initialize(actions[key] || (actions[key] = {}), action, name)
Expand All @@ -63,7 +66,7 @@ export function app(props) {

function update(withState) {
if (typeof withState === "function") {
return withState(update)
return update(withState(appState))
}
if (withState && (withState = emit("update", merge(appState, withState)))) {
requestRender((appState = withState))
Expand Down

0 comments on commit 2b35ff2

Please sign in to comment.