Using Redux with Wechaty
Wrap Wechaty with Redux Actions & Reducers for Easy State Management
Image Source: Managing your React state with Redux
What is Redux​
Redux is a predictable state container designed to help you write JavaScript apps that behave consistently across client, server, and native environments
Why use Redux with Wechaty​
Redux is used for application state management.
- makes the state predictable
- easier to trace which action causes any change
- makes it easier to test, maintain and debug
What is Ducks​
🦆🦆🦆Ducks is a Reducer Bundles Manager that Implementing the Redux Ducks Modular Proposal with Great Convenience.
Image Credit: Alamy
Ducks offers a method of handling redux module packaging, installing, and running with your Redux store, with middleware support.
See Ducks is a Reducer Bundles Manager that Implements the Redux Ducks Modular Proposal with Great Convenience. It offers a method of handling redux module packaging, installing, and running with your Redux store, with middleware support.
Usage​
Install​
npm install wechaty-redux
Vanilla Redux with Wechaty Redux Plugin​
Vanilla Redux means using plain Redux without any additional libraries like Ducks.
import {
createStore,
applyMiddleware,
} from 'redux'
import {
createEpicMiddleware,
combineEpics,
} from 'redux-observable'
import { Wechaty } from 'wechaty'
import {
WechatyRedux,
Api,
} from 'wechaty-redux'
// 1. Configure Store with RxJS Epic Middleware for Wechaty Ducks API
const epicMiddleware = createEpicMiddleware()
const store = createStore(
Api.default,
applyMiddleware(epicMiddleware),
)
const rootEpic = combineEpics(...Object.values(Api.epics))
epicMiddleware.run(rootEpic)
// 2. Instanciate Wechaty and Install Redux Plugin
const bot = Wechaty.instance({ puppet: 'wechaty-puppet-mock' })
bot.use(WechatyRedux({ store }))
// 3. Using Redux Store with Wechaty Ducks API!
store.subscribe(() => console.info(store.getState()))
store.dispatch(Api.actions.ding(bot.id, 'dispatch a ding action'))
// The above code 👆 is exactly do the same thing with the following code 👇 :
Api.operations.ding(store.dispatch)(bot.id, 'call ding from operations')
Ducks Proposal Style for Wechaty Redux Plugin​
import { Wechaty } from 'wechaty'
import { Ducks } from 'ducks'
import {
WechatyRedux,
Api,
} from 'wechaty-redux'
// 1. Ducksify Wechaty Redux API
const ducks = new Ducks({ wechaty: Api })
const store = ducks.configureStore()
// 2. Instanciate Wechaty with Redux Plugin
const bot = Wechaty.instance({ puppet: 'wechaty-puppet-mock' })
bot.use(WechatyRedux({ store }))
// 3. Using Redux Store with Wechaty Ducks API!
// (With the Power of Ducks / Ducksify)
const wechatyDuck = ducks.ducksify('wechaty')
store.subscribe(() => console.info(store.getState()))
wechatyDuck.operations.ding(bot.id, 'Ducksify Style ding!')
Ducks Api​
Ducks is very easy to use, because one of the goals of designing it is to maximize the convenience. To know more about the Ducks Api,please refer here.