Usage with Redux

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:

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:

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:

This require us to put ReduxStore to the bottom in the list of the providers:

That's how we use Redux with Deviation!

Last updated

Was this helpful?