@reduxjs/toolkit#AnyAction TypeScript Examples
The following examples show how to use
@reduxjs/toolkit#AnyAction.
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: notificationsSlice.ts From server with MIT License | 6 votes |
loadMoreNotifications = (): ThunkAction<void, RootState, unknown, AnyAction> => {
return async (dispatch, getState) => {
if (getState().notifications.loadingMore) {
return
}
dispatch(setLoadingMore())
const notifications = getState().notifications.notifications
const lastNotification = notifications[notifications.length - 1]
const newNotifications = await api.getNotifications(lastNotification['id'])
if (newNotifications.length !== 0) {
dispatch(setNotifications(notifications.concat(newNotifications)))
}
dispatch(unsetLoadingMore())
}
}
Example #2
Source File: game.ts From minesweeper with MIT License | 6 votes |
recursiveUpdate =
(prevGameField: Field): ThunkAction<void, RootState, unknown, AnyAction> =>
(dispatch, getState) =>
setTimeout(() => {
const { isGameStarted, isTimerRunning, gameField } = getState().game;
const isTheSameGame = gameField === prevGameField;
if (isGameStarted && isTimerRunning && isTheSameGame) {
dispatch(actions.updateTime());
dispatch(recursiveUpdate(gameField));
}
}, 1000)
Example #3
Source File: game.ts From minesweeper with MIT License | 6 votes |
runTimer =
(): ThunkAction<void, RootState, unknown, AnyAction> =>
(dispatch, getState) => {
const { isGameStarted, isTimerRunning, gameField } = getState().game;
if (isGameStarted && !isTimerRunning) {
dispatch(actions.setTimerActive());
dispatch(recursiveUpdate(gameField));
}
}
Example #4
Source File: homeSlice.ts From server with MIT License | 6 votes |
loadMorePosts = (): ThunkAction<void, RootState, unknown, AnyAction> => {
return async (dispatch, getState) => {
if (getState().home.loadingMore) {
return
}
dispatch(setLoadingMore())
const homePosts = getState().home.posts
const lastPost = homePosts[homePosts.length - 1]
const newPosts = await api.getHome(lastPost['id'])
if (newPosts.length !== 0) {
dispatch(setPosts(homePosts.concat(newPosts)))
} else {
dispatch(setNoMore())
}
dispatch(unsetLoadingMore())
}
}
Example #5
Source File: homeSlice.ts From server with MIT License | 6 votes |
pollPosts = (): ThunkAction<void, RootState, unknown, AnyAction> => {
return async (dispatch, getState) => {
const homePosts = getState().home.posts
if (homePosts.length === 0 || getState().home.loading || getState().home.polling) {
return
}
dispatch(setPolling())
const newPosts = await api.pollHome(homePosts[0].id)
if (newPosts.length !== 0) {
dispatch(setPosts([...newPosts, ...homePosts]))
}
dispatch(unsetPolling())
}
}
Example #6
Source File: Tools.ts From foundation-lib-spa-core with Apache License 2.0 | 6 votes |
export function observeStore<T = any, S = any, A extends Action<any> = AnyAction, M extends Middlewares<S> = Middlewares<S>>
(
store: EnhancedStore<S, A, M>,
select: (state: S) => T,
onChange: (state: T) => void
) : Unsubscribe
{
let currentState : any;
function handleChange() {
const nextState = select(store.getState());
if (nextState !== currentState) {
currentState = nextState;
onChange(currentState);
}
}
const unsubscribe = store.subscribe(handleChange);
handleChange();
return unsubscribe;
}
Example #7
Source File: notificationsSlice.ts From server with MIT License | 6 votes |
pollNotifications = (): ThunkAction<void, RootState, unknown, AnyAction> => {
return async (dispatch, getState) => {
const notifications = getState().notifications.notifications
if (notifications.length === 0 || getState().notifications.loadingMore) {
return
}
dispatch(setPolling())
const newNotifications = await api.pollNotifications(notifications[0].id)
if (newNotifications.length !== 0) {
dispatch(setNotifications([...newNotifications, ...notifications]))
}
dispatch(unsetPolling())
}
}
Example #8
Source File: notificationStateSlice.ts From prism-frontend with MIT License | 6 votes |
errorToNotificationMiddleware: Middleware<{}, RootState> = () => (
dispatch: AppDispatch,
) => (action: AnyAction) => {
let dispatchResult;
try {
// catch sync errors
// eslint-disable-next-line fp/no-mutation
dispatchResult = dispatch(action);
} catch (err) {
dispatch(
addNotification({
type: 'error',
message: err.message || err,
}),
);
throw err;
}
// typical layout for rejected thunk e.g mapState/loadLayerData/rejected
const thunkRejectedRegex = /^[A-z]+\/[A-z]+\/rejected$/;
if (thunkRejectedRegex.test(action.type)) {
const errorMessage = action.error.message || action.error;
dispatch(
addNotification({
type: 'error',
message: errorMessage,
}),
);
console.error(`Above error(s) caused by: ${errorMessage}`);
}
return dispatchResult;
}
Example #9
Source File: Reducer.ts From Teyvat.moe with GNU General Public License v3.0 | 6 votes |
mapReducer = (currentState: MapState | null, action: AnyAction): MapState => ({
auth: authReducer(selectSliceAuth(currentState), action),
completed: completedReducer(selectSliceCompleted(currentState), action),
displayed: displayedReducer(selectSliceDisplayed(currentState), action),
editor: editorReducer(selectSliceEditor(currentState), action),
error: errorReducer(selectSliceError(currentState), action),
interface: interfaceReducer(selectSliceInterface(currentState), action),
loading: loadingReducer(selectSliceLoading(currentState), action),
options: optionsReducer(selectSliceOptions(currentState), action),
})
Example #10
Source File: notificationsSlice.ts From server with MIT License | 6 votes |
markNotificationAsRead = (notificationId: string): ThunkAction<void, RootState, unknown, AnyAction> => {
return async (dispatch, getState) => {
await api.markNotificationAsRead(notificationId)
dispatch(setNotifications(getState().notifications.notifications.map(n => {
if (n.id === notificationId) {
return {
...n, unread: false
}
}
return n
}))) }
}
Example #11
Source File: notificationsSlice.ts From server with MIT License | 6 votes |
markAllNotificationsAsRead= (): ThunkAction<void, RootState, unknown, AnyAction> => {
return async (dispatch, getState) => {
await api.markAllNotificationsAsRead()
dispatch(setNotifications(getState().notifications.notifications.map(n => {
return {
...n,
unread: false
}
})))
}
}
Example #12
Source File: navModel.ts From grafana-chinese with Apache License 2.0 | 6 votes |
navIndexReducer = (state: NavIndex = initialState, action: AnyAction): NavIndex => {
if (updateNavIndex.match(action)) {
const newPages: NavIndex = {};
const payload = action.payload;
for (const node of payload.children) {
newPages[node.id] = {
...node,
parentItem: payload,
};
}
return { ...state, ...newPages };
}
return state;
}
Example #13
Source File: hooks.ts From bluebubbles-server with Apache License 2.0 | 5 votes |
useAppDispatch = (): Dispatch<AnyAction> => useDispatch<AppDispatch>()
Example #14
Source File: notificationsSlice.ts From server with MIT License | 5 votes |
loadNotifications = (): ThunkAction<void, RootState, unknown, AnyAction> => {
return async (dispatch) => {
dispatch(setNotifications(await api.getNotifications()))
dispatch(unsetLoading())
}
}
Example #15
Source File: meSlice.ts From server with MIT License | 5 votes |
loadMe = (): ThunkAction<void, RootState, unknown, AnyAction> => {
return async (dispatch) => {
dispatch(setLoading())
dispatch(setMe(await api.getMe()))
dispatch(unsetLoading())
}
}
Example #16
Source File: homeSlice.ts From server with MIT License | 5 votes |
loadPosts = (): ThunkAction<void, RootState, unknown, AnyAction> => {
return async (dispatch) => {
dispatch(setPosts(await api.getHome()))
dispatch(unsetLoading())
}
}
Example #17
Source File: reducers.ts From grafana-chinese with Apache License 2.0 | 5 votes |
dataSourcesReducer = (state: DataSourcesState = initialState, action: AnyAction): DataSourcesState => {
if (dataSourcesLoaded.match(action)) {
return {
...state,
hasFetched: true,
dataSources: action.payload,
dataSourcesCount: action.payload.length,
};
}
if (dataSourceLoaded.match(action)) {
return { ...state, dataSource: action.payload };
}
if (setDataSourcesSearchQuery.match(action)) {
return { ...state, searchQuery: action.payload };
}
if (setDataSourcesLayoutMode.match(action)) {
return { ...state, layoutMode: action.payload };
}
if (dataSourcePluginsLoad.match(action)) {
return { ...state, plugins: [], isLoadingDataSources: true };
}
if (dataSourcePluginsLoaded.match(action)) {
return {
...state,
plugins: action.payload.plugins,
categories: action.payload.categories,
isLoadingDataSources: false,
};
}
if (setDataSourceTypeSearchQuery.match(action)) {
return { ...state, dataSourceTypeSearchQuery: action.payload };
}
if (dataSourceMetaLoaded.match(action)) {
return { ...state, dataSourceMeta: action.payload };
}
if (setDataSourceName.match(action)) {
return { ...state, dataSource: { ...state.dataSource, name: action.payload } };
}
if (setIsDefault.match(action)) {
return {
...state,
dataSource: { ...state.dataSource, isDefault: action.payload },
};
}
return state;
}
Example #18
Source File: reducers.ts From grafana-chinese with Apache License 2.0 | 5 votes |
dataSourceSettingsReducer = (
state: DataSourceSettingsState = initialDataSourceSettingsState,
action: AnyAction
): DataSourceSettingsState => {
if (initDataSourceSettingsSucceeded.match(action)) {
return { ...state, plugin: action.payload, loadError: null };
}
if (initDataSourceSettingsFailed.match(action)) {
return { ...state, plugin: null, loadError: action.payload.message };
}
if (testDataSourceStarting.match(action)) {
return {
...state,
testingStatus: {
message: 'Testing...',
status: 'info',
},
};
}
if (testDataSourceSucceeded.match(action)) {
return {
...state,
testingStatus: {
status: action.payload.status,
message: action.payload.message,
},
};
}
if (testDataSourceFailed.match(action)) {
return {
...state,
testingStatus: {
status: 'error',
message: action.payload.message,
},
};
}
return state;
}
Example #19
Source File: Tools.d.ts From foundation-lib-spa-core with Apache License 2.0 | 5 votes |
export declare function setLanguage<S = any, A extends Action<any> = AnyAction, M extends Middlewares<S> = Middlewares<S>>(newLanguage: string, store: EnhancedStore<S, A, M>): void;
Example #20
Source File: Tools.d.ts From foundation-lib-spa-core with Apache License 2.0 | 5 votes |
export declare function observeStore<T = any, S = any, A extends Action<any> = AnyAction, M extends Middlewares<S> = Middlewares<S>>(store: EnhancedStore<S, A, M>, select: (state: S) => T, onChange: (state: T) => void): Unsubscribe;
Example #21
Source File: Spa.d.ts From foundation-lib-spa-core with Apache License 2.0 | 5 votes |
invoke<T>(action: AnyAction): T;
Example #22
Source File: Spa.d.ts From foundation-lib-spa-core with Apache License 2.0 | 5 votes |
dispatch<T>(action: AnyAction): T;
Example #23
Source File: Tools.ts From foundation-lib-spa-core with Apache License 2.0 | 5 votes |
export function setLanguage<S = any, A extends Action<any> = AnyAction, M extends Middlewares<S> = Middlewares<S>>(newLanguage: string, store: EnhancedStore<S,A,M>) : void
{
const action : A = {
type: 'OptiContentCloud/SetState',
currentLanguage: newLanguage
} as unknown as A;
store.dispatch(action);
}
Example #24
Source File: Spa.ts From foundation-lib-spa-core with Apache License 2.0 | 5 votes |
public invoke<T>(action: AnyAction): T {
this.enforceInitialized();
return this._state.dispatch(action) as unknown as T;
}
Example #25
Source File: Spa.ts From foundation-lib-spa-core with Apache License 2.0 | 5 votes |
public dispatch<T>(action: AnyAction): T {
this.enforceInitialized();
return this._state.dispatch(action) as unknown as T
}
Example #26
Source File: Reducer.ts From Teyvat.moe with GNU General Public License v3.0 | 5 votes |
commonReducer = (currentState: CommonState | null, action: AnyAction): CommonState => ({
i18n: i18nReducer(selectSliceI18n(currentState), action),
notify: notifyReducer(selectSliceNotify(currentState), action),
})
Example #27
Source File: Reducer.ts From Teyvat.moe with GNU General Public License v3.0 | 5 votes |
reducer = (currentState: AppState = initialState, action: AnyAction): AppState => ({
common: commonReducer(selectNamespaceCommon(currentState), action),
map: mapReducer(selectNamespaceMap(currentState), action),
})
Example #28
Source File: Navigation.tsx From bluebubbles-server with Apache License 2.0 | 5 votes |
closeNotification = (closeFunc: () => void, dispatch: React.Dispatch<AnyAction>) => {
dispatch(readAll());
closeFunc();
}
Example #29
Source File: actions.ts From webminidisc with GNU General Public License v2.0 | 4 votes |
export function convertAndUpload(files: File[], requestedFormat: UploadFormat, titleFormat: TitleFormatType) {
return async function(dispatch: AppDispatch, getState: () => RootState) {
const { audioExportService, netmdService } = serviceRegistry;
await netmdService?.stop();
dispatch(batchActions([uploadDialogActions.setVisible(true), uploadDialogActions.setCancelUpload(false)]));
const updateProgressCallback = ({ written, encrypted, total }: { written: number; encrypted: number; total: number }) => {
dispatch(uploadDialogActions.setWriteProgress({ written, encrypted, total }));
};
const hasUploadBeenCancelled = () => {
return getState().uploadDialog.cancelled;
};
function showFinishedNotificationIfNeeded() {
const { notifyWhenFinished, hasNotificationSupport } = getState().appState;
if (!hasNotificationSupport || !notifyWhenFinished) {
return;
}
const notification = new Notification('MiniDisc recording completed', {
icon: NotificationCompleteIconUrl,
});
notification.onclick = function() {
window.focus();
this.close();
};
}
let trackUpdate: {
current: number;
converting: number;
total: number;
titleCurrent: string;
titleConverting: string;
} = {
current: 0,
converting: 0,
total: files.length,
titleCurrent: '',
titleConverting: '',
};
const updateTrack = () => {
dispatch(uploadDialogActions.setTrackProgress(trackUpdate));
};
let conversionIterator = async function*(files: File[]) {
let converted: Promise<{ file: File; data: ArrayBuffer; format: Wireformat }>[] = [];
let i = 0;
function convertNext() {
if (i === files.length || hasUploadBeenCancelled()) {
trackUpdate.converting = i;
trackUpdate.titleConverting = ``;
updateTrack();
return;
}
let f = files[i];
trackUpdate.converting = i;
trackUpdate.titleConverting = f.name;
updateTrack();
i++;
converted.push(
new Promise(async (resolve, reject) => {
let data: ArrayBuffer;
let format: Wireformat;
try {
await audioExportService!.prepare(f);
({ data, format } = await audioExportService!.export({ requestedFormat }));
convertNext();
resolve({ file: f, data: data, format: format });
} catch (err) {
error = err;
errorMessage = `${f.name}: Unsupported or unrecognized format`;
reject(err);
}
})
);
}
convertNext();
let j = 0;
while (j < converted.length) {
yield await converted[j];
delete converted[j];
j++;
}
};
let disc = getState().main.disc;
let useFullWidth = getState().appState.fullWidthSupport;
let availableCharacters = getAvailableCharsForTitle(disc!);
let error: any;
let errorMessage = ``;
let i = 1;
for await (let item of conversionIterator(files)) {
if (hasUploadBeenCancelled()) {
break;
}
const { file, data, format } = item;
let title = file.name;
try {
title = await getTrackNameFromMediaTags(file, titleFormat);
} catch (err) {
console.error(err);
}
const fixLength = (l: number) => Math.ceil(l / 7) * 7;
let halfWidthTitle = title.substr(0, Math.min(getHalfWidthTitleLength(title), availableCharacters));
availableCharacters -= fixLength(getHalfWidthTitleLength(halfWidthTitle));
let fullWidthTitle = '';
if (useFullWidth) {
fullWidthTitle = title.substr(0, Math.min(title.length * 2, availableCharacters, 210 /* limit is 105 */) / 2);
availableCharacters -= fixLength(fullWidthTitle.length * 2);
}
trackUpdate.current = i++;
trackUpdate.titleCurrent = halfWidthTitle;
updateTrack();
updateProgressCallback({ written: 0, encrypted: 0, total: 100 });
try {
await netmdService?.upload(halfWidthTitle, fullWidthTitle, data, format, updateProgressCallback);
} catch (err) {
error = err;
errorMessage = `${file.name}: Error uploading to device. There might not be enough space left.`;
break;
}
}
let actionToDispatch: AnyAction[] = [uploadDialogActions.setVisible(false)];
if (error) {
console.error(error);
actionToDispatch = actionToDispatch.concat([
errorDialogAction.setVisible(true),
errorDialogAction.setErrorMessage(errorMessage),
]);
}
dispatch(batchActions(actionToDispatch));
showFinishedNotificationIfNeeded();
listContent()(dispatch);
};
}