Skip to content

Less boilerplate while creating your reducers! 🚀

Notifications You must be signed in to change notification settings

renancarvalho/reswitch

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

reswitch v0.1.0

Write your reducers with less boilerplate!

Install

npm install --save reswitch

Usage

Through its simplest usage, within a fictional userReducer.js reducer:

yourapp/reducers/usersReducer.js

import reswitch from 'reswitch'

import {
  USERS_GET,
  USERS_GET__SUCCESS,
  USERS_GET__FAILURE
} from 'reducers/users'

const defaultState = {areLoading: false, hasError: false, users: null}

function users(state = {
  areLoading: false,
  hasError:   false,
  users:      null
}, action) {
  return reswitch(
    USERS_GET,          {...defaultState, areLoading: true},
    USERS_GET__SUCCESS, {...defaultState, users: action.users},
    USERS_GET__FAILURE, {...defaultState, hasError: true},
  )(state, action.type)
}

export default users

Or you can even hang with functions!

return reswitch(
  USERS_GET,          {...defaultState, areLoading: true},
  USERS_GET__SUCCESS, {...defaultState, users: action.users},
  USERS_GET__FAILURE, () => ({...state, action.error})
)(state, action.type)

Important: In case none of the actions match, then state will be used instead as the default. Maybe you want to use a different fashion, then just leave your reswitch with an odd number of arguments and it will pick the last one as the new default:

return reswitch(
  USERS_GET,          {...defaultState, areLoading: true},
  USERS_GET__SUCCESS, {...defaultState, users: action.users},
  USERS_GET__FAILURE, () => ({...state, action.error}),

  () => ({...defaultState, areAdmin: false})
)(state, action.type)

In the above's example we're defining the last argument as a function, but it doesn't need to be. You can use a plain object—or even a complex one!—if you need.

Motivation

I don't like those huge amounts of switches. Although in the official Redux's website they're saying that switches aren't the real boilerplate, I still don't like to use it. It looks like a boilerplate and for me that's reason enough;

License

MIT

About

Less boilerplate while creating your reducers! 🚀

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%