Redux is a great framework for its predictable and tooling. Though its complexity, it's worth that some developers might want to integrate Deviation with Redux. Like NgRedux, we also have Redux Deviation. This make Redux implementation much more cleaner and predictable:
Create a Redux Store
First of all, we need to create a container for Redux Store. It's simple:
Copy export class ReduxStore extends Store {
rootReducer = combineReducers ({ })
store = createStore ( this .rootReducer)
getState () {
return this . store .getState ()
}
dispatch (action) {
this . store .dispatch (action)
}
}
Then, we can also create a container for each reducer and its action creators:
Copy enum CounterAction {
INCREMENT = 'INCREMENT'
DECREMENT = 'DECREMENT'
}
@ Inject ({
reduxStore : () => ReduxStore
})
export class CounterStore extends Store {
get reduxStore () {
return this . props .reduxStore
}
state = {
counter : 0
}
storeDidMount () {
this
.reduxStore
.dispatch (() =>
this .setState ( this . reduxStore .getState ().counterStore)
)
}
increment = () => {
this . reduxStore .dispatch ({
type : CounterAction . INCREMENT
})
}
decrement = () => {
this . reduxStore .dispatch ({
type : CounterAction . DECREMENT
})
}
counterReducer (state = this .state , action) {
switch ( action .type) {
case CounterAction . INCREMENT :
return {
... state ,
counter : counter + 1
}
case CounterAction . DECREMENT :
return {
... state ,
counter : counter - 1
}
default :
return state
}
}
}
Then, don't forget to add counterReducer
to the list of reducers:
Copy @ Inject ({
counterStore : () => CounterStore
})
export class ReduxStore extends Store {
rootReducer = combineReducers ({
counterStore : this . props . counterStore .counterReducer
})
}
This require us to put ReduxStore
to the bottom in the list of the providers:
Copy ReactDOM .render (
< Deviation providers = {[CounterStore , ReduxStore]}>
<AppRoot />
</Deviation>,
document.getElementById('root')
)
That's how we use Redux with Deviation!