use redux to store view state
npm install with-view-state```
npm install with-view-state --save
people use redux may confused when to use setState and when to use dispatch reducer action.
this package is aimed to store the state to redux. Forget setState, enjoy redux!
usefull for these situations:
- show/hide modal
- submitting/done button
- loading/hide spinner
`javascript
import { combineReducers } from 'redux';
import { reducer as viewState } from 'with-view-state';
// reducers = ....
export default combineReducers({
...reducers,
viewState
});
`
`javascript
import withViewState from 'with-view-state'
// YourComponent : .....
const config = {
id: 'myComponent', //defualt is a random string, set some name if you need
}
const wrapped = withViewState(config)(YourComponent)
`
`javascript
class YourComponent extends Component{
onClick = () => {
this.props.setViewState({ submitting: true } )
}
render() {
const { viewState } = this.props;
const { submitting } = viewState;
// ....
}
}
`
or dummy component:
`javascript
const YouCompoent = ({viewState, setViewState}) => {
//....
}
`
The configure that the decorator withViewState() accepts.
default is
``
(store) => store.viewState
if your reducer is not at sotre.viewState, set another function
default is
`
(state) => ({viewState: state})
`
this makes the component use props.viewState to get the state of the view.
you can use another function as you wish
this function will first dispatch a indicator start action and then dispatch the action
with a meta fields onCompleteAction which is the idicator complete action.
when indicator is a string, it will be as the field name, in start it will be true, on completed, it will be false,
if indicator is a object, it will be itself on start, and on completed, it will be a object with the same keys,
but every value si false
for explain:
`javascript
indicator = "submitting"
//on start :
viewState = {submitting : true, ...others }
//completed:
viewState = {submitting : false, ...others }
`
or
`javascript
idicator = { spin: "double-bounce" , submitting: true }
//on start:
viewState = { spin: "double-bounce", submitting: true, ...others }
//completed:
viewState = { spin: false, submitting: false, ...others }
``
Notice:
You must use some async handlers like redux-saga to dispatch the onCompleteAction.