From ac1be834dbdfa3c9e6a58ffb25fbca0f2fcd752b Mon Sep 17 00:00:00 2001 From: Nicola Molinari Date: Fri, 5 Jun 2015 22:12:17 +0200 Subject: [PATCH] Allow to read state by store on action creator callback. Refs #43 Keep trailing whitespaces Keep async action out of example for now --- README.md | 6 +++--- examples/counter/actions/CounterActions.js | 5 +++-- src/createDispatcher.js | 7 ++++++- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index e3489e28e3..0be5301b2e 100644 --- a/README.md +++ b/README.md @@ -62,10 +62,10 @@ export function incrementAsync() { }; } -// Could also look into state in the callback form +// Could also read state of a store in the callback form export function incrementIfOdd() { - return (dispatch, state) => { - if (state.counterStore % 2 === 0) { + return (dispatch, read) => { + if (read(counterStore) % 2 === 0) { return; } diff --git a/examples/counter/actions/CounterActions.js b/examples/counter/actions/CounterActions.js index 30ca2f9781..f4e4e6540d 100644 --- a/examples/counter/actions/CounterActions.js +++ b/examples/counter/actions/CounterActions.js @@ -2,6 +2,7 @@ import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../constants/ActionTypes'; +import { counterStore } from '../stores'; export function increment() { return { @@ -10,8 +11,8 @@ export function increment() { } export function incrementIfOdd() { - return (dispatch, state) => { - if (state.counterStore.counter % 2 === 0) { + return (dispatch, read) => { + if (read(counterStore) % 2 === 0) { return; } diff --git a/src/createDispatcher.js b/src/createDispatcher.js index f7fd86e4d9..206eb03d2b 100644 --- a/src/createDispatcher.js +++ b/src/createDispatcher.js @@ -121,7 +121,7 @@ export default function createDispatcher() { const action = actionCreator(...args); if (typeof action === 'function') { // Callback-style action creator - action(dispatch, currentState); + action(dispatch, read); } else { // Simple action creator dispatch(action); @@ -129,6 +129,11 @@ export default function createDispatcher() { }; } + // Allow to read the state of a store + function read(store) { + return currentState[getStoreKey(store)]; + } + return { wrapActionCreator, observeStores,