redux#Dispatch TypeScript Examples
The following examples show how to use
redux#Dispatch.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From polkabtc-ui with Apache License 2.0 | 7 votes |
updateBalances = async (
dispatch: Dispatch,
address: string,
currentBalanceDOT: string,
currentBalancePolkaBTC: string
): Promise<void> => {
const accountId = window.polkaBTC.api.createType(ACCOUNT_ID_TYPE_NAME, address);
const balancePolkaBTC = (await window.polkaBTC.treasury.balance(accountId)).toString();
const balanceDOT = (await window.polkaBTC.collateral.balance(accountId)).toString();
if (currentBalanceDOT !== balanceDOT) {
dispatch(updateBalanceDOTAction(balanceDOT));
}
if (currentBalancePolkaBTC !== balancePolkaBTC) {
dispatch(updateBalancePolkaBTCAction(balancePolkaBTC));
}
}
Example #2
Source File: index.ts From shippo with MIT License | 6 votes |
createStore = (compose?: (...middleware: Middleware[]) => StoreEnhancer) => {
compose = compose || applyMiddleware
const middleware: Array<Middleware> = [thunkMiddleware]
const stores = create(reducers, compose(...middleware))
const thunkDispatch: ThunkDispatch = (action) => stores.dispatch<any>(action)
const dispatch: Dispatch = (action) => stores.dispatch<any>(action)
const selector = <T>(selector: (store: IStores) => T) => selector(stores.getState())
return {
stores,
thunkDispatch,
dispatch,
selector,
}
}
Example #3
Source File: newsletter-dispatcher.ts From pola-web with MIT License | 6 votes |
newsletterDispatcher = {
subscribeEmail: (email: string, name?: string) => async (dispatch: Dispatch, getState: () => IPolaState) => {
try {
const follower = Follower.create(email, name);
const service = NewsletterService.getInstance();
await dispatch(actions.Subscribing(follower));
try {
const context = await service.subscribeNewsletter(follower);
await dispatch(actions.SubscriptionSuccess(follower, context));
} catch (error: unknown) {
const subscriptionError = error instanceof SubscriptionError ? error : new SubscriptionError(error);
await dispatch(actions.SubscriptionFailure(follower, subscriptionError));
}
} catch (error: unknown) {
console.error(error);
}
},
}
Example #4
Source File: CopyMeetingPage.tsx From msteams-meetings-template with MIT License | 6 votes |
mapDispatchToProps = (dispatch: Dispatch) => ({
onCopyToClipboard: (meeting?: OnlineMeeting) => {
const str =
document.getElementById('copy')?.innerHTML ||
translate('copyMeetingPage.failed.copy');
function listener(e: ClipboardEvent) {
if (!e || !e.clipboardData) {
return;
}
e.clipboardData.setData('text/html', str);
e.clipboardData.setData(
'text/plain',
meeting?.joinWebUrl ?? translate('copyMeetingPage.failed.copy')
);
e.preventDefault();
}
document.addEventListener('copy', listener);
document.execCommand('copy');
document.removeEventListener('copy', listener);
}
})
Example #5
Source File: metamask-error-wrap.ts From rugenerous-frontend with MIT License | 6 votes |
metamaskErrorWrap = (err: any, dispatch: Dispatch) => {
let text = messages.something_wrong;
if (err.code && err.code === -32603) {
if (err.message.indexOf("ds-math-sub-underflow") >= 0) {
text = "You may be trying to bond more than your balance! Error code: 32603. Message: ds-math-sub-underflow";
}
if (err.data && err.data.message) {
text = err.data.message.includes(":") ? err.data.message.split(":")[1].trim() : err.data.data || err.data.message;
}
if (err.data && err.data.message && err.data.message.includes("gas required exceeds allowance")) {
text = "Insufficient balance to make a transaction";
}
if (err.data && err.data.message && err.data.message.includes("Bond too small")) {
text = "Bond too small";
}
}
if (err.code && err.code === 4001) {
if (err.message.includes("User denied transaction signature")) {
text = "User denied transaction signature";
}
}
return dispatch(error({ text, error: err }));
}
Example #6
Source File: websocket-chat-container.ts From react-spring-messenger-project with MIT License | 6 votes |
mapDispatchToProps = (dispatch: Dispatch) => {
return {
fetchMessages: (model: ReduxModel) => dispatch(fetchGroupMessages(model)),
getGroupMessages: (model: ReduxModel) => dispatch(getGroupMessages(model)),
setCurrentActiveGroup: (groupUrl: string) => dispatch(setCurrentActiveGroup(groupUrl)),
sendWsMessage: (message: ReduxModel) => dispatch(sendWsMessage(message)),
markMessageAsSeen: (model: ReduxModel) => dispatch(markMessageAsSeen(model))
}
}
Example #7
Source File: metamask-error-wrap.ts From wonderland-frontend with MIT License | 6 votes |
metamaskErrorWrap = (err: any, dispatch: Dispatch) => {
let text = messages.something_wrong;
if (err.code && err.code === -32603) {
if (err.message.indexOf("ds-math-sub-underflow") >= 0) {
text = "You may be trying to bond more than your balance! Error code: 32603. Message: ds-math-sub-underflow";
}
if (err.data && err.data.message) {
text = err.data.message.includes(":") ? err.data.message.split(":")[1].trim() : err.data.data || err.data.message;
}
if (err.data && err.data.message && err.data.message.includes("gas required exceeds allowance")) {
text = "Insufficient balance to make a transaction";
}
if (err.data && err.data.message && err.data.message.includes("Bond too small")) {
text = "Bond too small";
}
}
if (err.code && err.code === 4001) {
if (err.message.includes("User denied transaction signature")) {
text = "User denied transaction signature";
}
}
return dispatch(error({ text, error: err }));
}
Example #8
Source File: createInterceptorMiddleware.ts From diagram-maker with Apache License 2.0 | 6 votes |
export function createInterceptorMiddleware<NodeType, EdgeType>(
actionInterceptor?: ActionInterceptor<NodeType, EdgeType>,
) {
return (store: MiddlewareAPI) => (next: Dispatch<Action>) => (action: Action) => {
if (!actionInterceptor) {
next(action);
return;
}
actionInterceptor(action, next, store.getState);
};
}
Example #9
Source File: deepLink-electron.ts From celo-web-wallet with MIT License | 6 votes |
function handleDeepLink(link: string, dispatch: Dispatch) {
if (!link || typeof link !== 'string' || !link.startsWith('celowallet://')) {
logger.debug('Ignoring invalid deep link', link)
return
}
const url = new URL(link)
const path = trimSlashes(url.pathname)
// WalletConnect URI
if (path === 'wc' && url.searchParams.has('uri')) {
logger.info('WalletConnect URI found in URL')
const uri = decodeURIComponent(url.searchParams.get('uri') || '')
const validation = validateWalletConnectForm({ uri })
if (validation.isValid) dispatch(initializeWcClient(uri))
}
}
Example #10
Source File: Preferences.tsx From baidu-pan-downloader with MIT License | 6 votes |
mapActionsToProps = (dispatch: Dispatch) => ({
closeModal: () => dispatch(interfaceModule.actions.change({ configModalOpen: false })),
setAutoStart: (e: React.ChangeEvent<HTMLInputElement>) => {
dispatch(interfaceModule.actions.change({ autoStart: e.target.checked }))
},
setDebug: (e: React.ChangeEvent<HTMLInputElement>) => {
dispatch(interfaceModule.actions.change({ debug: e.target.checked }))
},
setMaxDownloadCount: (e: React.ChangeEvent<HTMLSelectElement>) => {
const count = parseInt(e.target.value)
dispatch(interfaceModule.actions.change({ maxDownloadCount: count }))
},
setAppId: (e: React.ChangeEvent<HTMLInputElement>) => {
const appId = e.target.value
if (/^\d+$/.test(appId) || !appId) {
dispatch(interfaceModule.actions.change({ appId }))
}
},
})
Example #11
Source File: loadAddressBookFromStorage.ts From multisig-react with MIT License | 6 votes |
loadAddressBookFromStorage = () => async (dispatch: Dispatch): Promise<void> => {
try {
let storedAdBk = await getAddressBookFromStorage()
if (!storedAdBk) {
storedAdBk = []
}
const addressBook = buildAddressBook(storedAdBk)
dispatch(loadAddressBook(addressBook))
} catch (err) {
// eslint-disable-next-line
console.error('Error while loading active tokens from storage:', err)
}
}
Example #12
Source File: groupsActions.ts From asynqmon with MIT License | 6 votes |
export function listGroupsAsync(qname: string) {
return async (dispatch: Dispatch<GroupsActionTypes>) => {
dispatch({ type: LIST_GROUPS_BEGIN, queue: qname });
try {
const response = await listGroups(qname);
dispatch({
type: LIST_GROUPS_SUCCESS,
payload: response,
queue: qname,
});
} catch (error) {
console.error(`listGroupsAsync: ${toErrorStringWithHttpStatus(error)}`);
dispatch({
type: LIST_GROUPS_ERROR,
error: toErrorString(error),
queue: qname,
});
}
};
}
Example #13
Source File: block-height-watcher.ts From interbtc-ui with Apache License 2.0 | 6 votes |
export default async function fetchBtcRelayAndBitcoinHeight(dispatch: Dispatch, store: StoreState): Promise<void> {
const state = store.getState();
const { btcRelayHeight, bitcoinHeight, bridgeLoaded } = state.general;
if (!bridgeLoaded) return;
try {
const latestBtcRelayHeight = Number(await window.bridge.btcRelay.getLatestBlockHeight());
const latestBitcoinHeight = await window.bridge.electrsAPI.getLatestBlockHeight();
// update store only if there is a difference between the latest heights and current heights
if (btcRelayHeight !== latestBtcRelayHeight || bitcoinHeight !== latestBitcoinHeight) {
dispatch(updateHeightsAction(latestBtcRelayHeight, latestBitcoinHeight));
}
} catch (error) {
console.log(error);
}
}
Example #14
Source File: balances-watcher.ts From polkabtc-ui with Apache License 2.0 | 6 votes |
export default async function fetchBalances(dispatch: Dispatch, store: StoreState): Promise<void> {
const state = store.getState();
const { balanceDOT, balancePolkaBTC, polkaBtcLoaded, address } = state.general;
if (!polkaBtcLoaded) return;
try {
const accountId = window.polkaBTC.api.createType(ACCOUNT_ID_TYPE_NAME, address);
const latestBalancePolkaBTC = (await window.polkaBTC.treasury.balance(accountId)).toString();
const latestBalanceDOT = (await window.polkaBTC.collateral.balance(accountId)).toString();
// update store only if there is a difference between balances
if (latestBalanceDOT !== balanceDOT) {
dispatch(updateBalanceDOTAction(latestBalanceDOT));
}
if (latestBalancePolkaBTC !== balancePolkaBTC) {
dispatch(updateBalancePolkaBTCAction(latestBalancePolkaBTC));
}
} catch (error) {
console.log(error);
}
}
Example #15
Source File: LeftColumn.tsx From alchemist with MIT License | 6 votes |
mapDispatchToProps: MapDispatchToPropsFunction<ILeftColumnDispatch, Record<string, unknown>> = (dispatch: Dispatch): ILeftColumnDispatch => ({
onSetTargetReference: (arg) => dispatch(setTargetReferenceAction(arg)),
onAddDescriptor: (desc) => dispatch(addDescriptorAction(desc,false)),
onSetSelectedReferenceType: (type) => dispatch(setSelectedReferenceTypeAction(type)),
onClear: () => dispatch(clearAction()),
onPin: (pin, arg) => dispatch(pinDescAction(pin, arg)),
onRemove: (arg) => dispatch(removeDescAction(arg)),
onLock: (lock, arg) => dispatch(lockDescAction(lock, arg)),
onSetFilter: (type, subType, state) => dispatch(setFilterStateAction(type, subType, state)),
setListener: (enabled) => dispatch(setListenerAction(enabled)),
setAutoInspector: (enabled) => dispatch(setAutoInspectorAction(enabled)),
setSearchTerm: (str) => dispatch(setSearchTermAction(str)),
setRenameMode: (uuid: string, on: boolean) => dispatch(setRenameModeAction(uuid, on)),
onSelect: (operation: TSelectDescriptorOperation, uuid?: string) => dispatch(selectDescriptorAction(operation, uuid)),
onSetDontShowMarketplaceInfo: (enabled: boolean) => dispatch(setDontShowMarketplaceInfoAction(enabled)),
toggleDescGrouping:()=>dispatch(toggleDescriptorsGroupingAction()),
})
Example #16
Source File: hub.actions.ts From dashboard with Apache License 2.0 | 6 votes |
fetchHubImages = (
filters: FilterParams = defaultParams
): AppThunk<Promise<void>> => async (dispatch: Dispatch<HubActionTypes>) => {
try {
dispatch({
type: FETCH_HUB_IMAGES,
})
const images = await getHubImages(filters)
dispatch(fetchHubImagesSuccess(images))
} catch (e) {
dispatch(fetchHubImagesFailure(e))
}
}
Example #17
Source File: domains.ts From bob-extension with MIT License | 6 votes |
fetchDomainName = (name: string) => async (dispatch: Dispatch) => {
await dispatch(setFetching(true));
const domain: Domain = await postMessage({
type: MessageTypes.GET_DOMAIN_NAME,
payload: name,
});
await dispatch(setDomainName(domain));
await dispatch(setFetching(false));
}
Example #18
Source File: app.ts From flame with MIT License | 6 votes |
getApps =
() => async (dispatch: Dispatch<GetAppsAction<undefined | App[]>>) => {
dispatch({
type: ActionType.getApps,
payload: undefined,
});
try {
const res = await axios.get<ApiResponse<App[]>>('/api/apps', {
headers: applyAuth(),
});
dispatch({
type: ActionType.getAppsSuccess,
payload: res.data.data,
});
} catch (err) {
console.log(err);
}
}