Skip to content

Commit

Permalink
Merge pull request #44 from emmenko/read-state-by-store
Browse files Browse the repository at this point in the history
Allow to read state by store on action creator callback
  • Loading branch information
gaearon committed Jun 5, 2015
2 parents 319377c + ac1be83 commit f8d72b0
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
5 changes: 3 additions & 2 deletions examples/counter/actions/CounterActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
INCREMENT_COUNTER,
DECREMENT_COUNTER
} from '../constants/ActionTypes';
import { counterStore } from '../stores';

export function increment() {
return {
Expand All @@ -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;
}

Expand Down
7 changes: 6 additions & 1 deletion src/createDispatcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,19 @@ 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);
}
};
}

// Allow to read the state of a store
function read(store) {
return currentState[getStoreKey(store)];
}

return {
wrapActionCreator,
observeStores,
Expand Down

0 comments on commit f8d72b0

Please sign in to comment.