Last active
November 19, 2019 21:16
-
-
Save rainydio/5186f8ed55a8fda9df62f96a4231f0a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createAction, getType, ActionType } from "typesafe-actions"; | |
import { runSaga, stdChannel } from "redux-saga"; | |
import { fork, put, takeEvery, select } from "redux-saga/effects"; | |
const setWalletAttribute = createAction("STATE/SET_WALLET_ATTRIBUTE", | |
(address: string, attr: string, value: any) => ({ address, attr, value }), | |
)(); | |
type StateAction = ActionType<typeof setWalletAttribute>; | |
class State { | |
private readonly walletAttributes: Map<string, any>; | |
public constructor() { | |
this.walletAttributes = new Map<string, any>(); | |
} | |
public handle(action: StateAction) { | |
switch (action.type) { | |
case getType(setWalletAttribute): { | |
const { address, attr, value } = action.payload; | |
this.walletAttributes.set(`${address}.${attr}`, value); | |
break; | |
} | |
} | |
} | |
public getWalletAttribute(address: string, attr: string): any { | |
return this.walletAttributes.get(`${address}.${attr}`); | |
} | |
} | |
const channel = stdChannel(); | |
const state = new State(); | |
const store = { | |
channel, | |
dispatch(action) { | |
state.handle(action); | |
channel.put(action); | |
}, | |
getState() { | |
return state; | |
} | |
}; | |
const getWalletBalance = (state: State, address: string): number => { | |
return state.getWalletAttribute(address, "balance"); | |
}; | |
const addWalletBalance = createAction("WALLET/ADD_BALANCE", | |
(address: string, amount: number) => ({ address, amount }), | |
)(); | |
function * handleAddWalletBalance() { | |
yield takeEvery(addWalletBalance, function * (action: ReturnType<typeof addWalletBalance>) { | |
const { address, amount } = action.payload; | |
const balance = yield select(getWalletBalance, address); | |
yield put(setWalletAttribute(address, "balance", amount + (balance || 0))); | |
}); | |
} | |
function * rootSaga() { | |
yield fork(handleAddWalletBalance); | |
for (let i = 1; i <= 100; i++) { | |
yield put(addWalletBalance("wallet1", i)); | |
} | |
} | |
runSaga(store, rootSaga); | |
console.log("wallet1 balance", getWalletBalance(store.getState(), "wallet1")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment