Skip to content

Instantly share code, notes, and snippets.

@Dr-Nikson
Forked from vjpr/README.md
Last active January 14, 2019 06:35
Show Gist options
  • Select an option

  • Save Dr-Nikson/3c1b870f63dc0de67c38 to your computer and use it in GitHub Desktop.

Select an option

Save Dr-Nikson/3c1b870f63dc0de67c38 to your computer and use it in GitHub Desktop.
import {createActions} from 'redux-helpers'
export const CounterActions = createActions({
increment() {
return {}
},
async incrementIfOdd() {
// Debug
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, 1000)
})
let result = await promise
return result
},
//incrementIfOdd() {
//
// // Debug
// const promise = new Promise( (resolve, reject) => {
// setTimeout(() => {
// resolve()
// }, 1000)
// })
//
// return {
// types: ['INCREMENT_BEGIN', 'INCREMENT_SUCCESS', 'INCREMENT_FAILURE'],
// promise,
// }
//
//},
//incrementIfOdd() {
// return (dispatch, getState) => {
// const {counter} = getState()
// console.log(dispatch)
// if (counter % 2 === 0) return
// dispatch(CounterActions.increment())
// }
//},
incrementAsync() {
return dispatch => {
setTimeout(() => {
dispatch(CounterActions.increment())
}, 1000)
}
},
decrement() {
return {}
},
})
import React from 'react';
import {Provider} from 'redux/react';
import {RouteHandler} from 'react-router'
////////////////////////////////////////////////////////////////////////////////
// Redux
////////////////////////////////////////////////////////////////////////////////
import {createRedux, createDispatcher, composeStores} from 'redux';
import thunkMiddleware from 'redux/lib/middleware/thunk';
import {compose} from 'redux';
import {promiseMiddleware} from './helpers.js';
import * as stores from './store.js';
const store = composeStores(stores);
const dispatcher = createDispatcher(
store,
getState => [promiseMiddleware(), thunkMiddleware(getState)]
);
const redux = createRedux(dispatcher);
////////////////////////////////////////////////////////////////////////////////
// We use the above code - which this is shorthand for this, but adds our promise middleware.
//const redux = createRedux(stores)
////////////////////////////////////////////////////////////////////////////////
export default class App extends React.Component {
render() {
return (
<Provider redux={redux}>
{() =>
<RouteHandler/>
}
</Provider>
);
}
}

Redux is super lightweight...so it may be useful to add some helper utils on top of it to reduce some boilerplate. The goal of Redux is to keep these things in user-land, and so most likely these helpers (or anything like them) wouldn't make it into core.

It's important to note that this is just ONE (and not particularly thoroughly tested) way to accomplish the goal of reducing boilerplate in Redux. It borrows some ideas from Flummox and the way it generates action creator constants.

This will evolve, I'm sure, as time goes on and as Redux's API changes.

Some helper functions to reduce some boilerplate in Redux:

import _ from 'lodash';
import uniqueId from 'uniqueid';

// Create actions that don't need constants :)
export const createActions = (actionObj) => {
  const baseId = uniqueId();
  return _.zipObject(_.map(actionObj, (actionCreator, key) => {
    const actionId = `${baseId}-${key}`;
    const method = (...args) => {
      const result = actionCreator(...args);
      return {
        type: actionId,
        ...(result || {})
      };
    };
    method._id = actionId;
    return [key, method];
  }));
};

// Get action ids from actions created with `createActions`
export const getActionIds = (actionCreators) => {
  return _.mapValues(actionCreators, (value, key) => {
    return value._id;
  });
};

// Replace switch statements in stores (taken from the Redux README)
export const createStore = (initialState, handlers) => {
  return (state = initialState, action) =>
    handlers[action.type] ?
      handlers[action.type](state, action) :
      state;
};

They can be used like this:

Actions

import {createActions} from 'lib/utils/redux';

export const SocialPostActions = createActions({
  loadPosts(posts) {
    return { posts };
  }
});

Stores

import {default as Immutable, Map, List} from 'immutable';
import {createStore, getActionIds} from 'lib/utils/redux';

import {SocialPostActions} from 'lib/actions';

const initialState = Map({
  isLoaded: false,
  posts: List()
});

const actions = getActionIds(SocialPostActions);

export const posts = createStore(initialState, {
  [actions.loadPosts]: (state, action) => {
    return state.withMutations(s =>
      s.set('isLoaded', true).set('posts', Immutable.fromJS(action.posts))
    );
  }
});
import {createStore, getActionIds} from 'redux-helpers'
import {default as Immutable, Map, List} from 'immutable'
import {CounterActions} from '../actions'
const actions = getActionIds(CounterActions)
const initialState = 0
export const counter = createStore(initialState, {
[actions.incrementIfOdd+'-SUCCESS']: (state, actions) => {
return state + 5
},
['INCREMENT_SUCCESS']: (state, actions) => {
return state + 3
},
[actions.increment]: (state, actions) => {
return state + 1
},
[actions.decrement]: (state, actions) => {
return state - 1
},
})
@babsonmatt
Copy link

@iNikNik thanks for the great example. I'm having an issue using async/await (as provided in your first example). It seems that the async begin/success/failure types don't get added unless @AsyncAction() is used. Is this by design? It seems without it there's no way to know the function is async without knowing the result of the function and testing for Promise, but by that point the actionCreator has already been setup.

Any suggestions?

@Dr-Nikson
Copy link
Author

Hello @babsonmatt ! Thanks for the feedback, but I just forked @vjpr's gist)
async incrementAsync() returns a promise object. So, promise middleware will dispatch 3 types of action (begin, success, failure). But you can't handle these actions without asyncAction decorator.
Yep, it's by design:
https://gist.github.com/iNikNik/3c1b870f63dc0de67c38#file-helpers-js-L37-L46
https://gist.github.com/iNikNik/3c1b870f63dc0de67c38#file-helpers-js-L52-L56

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment