redux-setstate-reducer
Synchronus and functional setState with redux
Install
npm install redux-setstate-reducer
Basic Usage
;; // Create a reducer for the appconst reducer = ; const store = ; store; store;// {count: 1}store;// {count: -1}store;// {count: 10}
Why?
React's setState function is really powerful, BUT it is asynchronous. Redux is synchronous and allows you to implement setState functionally.
Redux-setstate-reducer also give you the ability to use redux without having to scaffold out boilerplate.
API
So how do you use the library?
setState(updater, [type])
The library's action creator to dispatch. You can either pass it a function or an object and it will execute the appropriate function in the reducer.
// ... console;// {count: 0} // Using a functionstore;// {count: 1} // Using the default merge operation ({...state, ...newState})store;// {count: 10}
type allows for targeting a reducer by it's type
// ... const reducer = const store = ; store; // Will ignore the global setState actionstore;// {count: 0} // Executes the correct typestore;// {count: 10}
createReducer([options])
Create a reducer for the app or just for a slice. options allow for customizing the reducer
Create a single reducer
// ... const reducer = ; const store = ; console;// {count: 0}
Create multiple reducer slices
// ... const reducer = ; const store = ; console;// {default: {}, first: {}, second: {}}
extendReducer(reducer, [options])
Extends an existing reducer. options alows for customizing the reducer
// ... const counterReducer = { }; const reducer = ;const store = ; store; // Will ignore the global setState actionstore;// 1 // Executes the correct typestore;// 10
options
initialState [Object = {}]
The initial state of the reducer. Defaults to an empty object.
// ... const reducer = ; const store = ; console;// {count: 0}
setState(state) [Function]
A custom function to run on the reducer. When run it will take the current state of the store and pass it into the function. This function overrides any arguments passed into the action creator.
// ... const reducer = ; const store = ; store; console;// {count: 1} store;// 2 // Anything passed into setState is ignoredstore;// 4 // Anything passed into setState is ignoredstore;// 8
type [String]
: 'A custom type for the reducer. This decouples it from the generic action creator and allows you to target a reducer specifically'
See setState type example