redux#AnyAction TypeScript Examples

The following examples show how to use redux#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: utils.ts    From diagram-maker with Apache License 2.0 7 votes vote down vote up
export function updateActionInLogger(action: Action) {
  const anyAction = action as AnyAction;
  const logger = document.getElementById('diagramMakerLogger');
  if (logger) {
    const type = createDivWithText(`Type is ${action.type}`);
    type.setAttribute('data-type', 'DiagramMaker.ActionType');
    type.setAttribute('data-id', action.type);
    logger.innerHTML = '';
    logger.appendChild(type);
    if (anyAction.payload) {
      const payload = createDivWithText(`Payload is ${JSON.stringify(anyAction.payload)}`);
      payload.setAttribute('data-type', 'DiagramMaker.ActionPayload');
      payload.setAttribute('data-id', action.type);
      logger.appendChild(payload);
    }
  }
}
Example #2
Source File: utils.ts    From diagram-maker-plugin-minimap with Apache License 2.0 7 votes vote down vote up
export function updateActionInLogger(action: Action) {
  const anyAction = action as AnyAction;
  const logger = document.getElementById('diagramMakerLogger');
  if (logger) {
    const type = createDivWithText(`Type is ${action.type}`);
    type.setAttribute('data-type', 'DiagramMaker.ActionType');
    type.setAttribute('data-id', action.type);
    logger.innerHTML = '';
    logger.appendChild(type);
    if (anyAction.payload) {
      const payload = createDivWithText(`Payload is ${JSON.stringify(anyAction.payload)}`);
      payload.setAttribute('data-type', 'DiagramMaker.ActionPayload');
      payload.setAttribute('data-id', action.type);
      logger.appendChild(payload);
    }
  }
}
Example #3
Source File: index.ts    From Pi-Tool with GNU General Public License v3.0 6 votes vote down vote up
export function setOverclockLevel(level: OverclockLevel):
    ThunkAction<void, any, unknown, AnyAction> {
    return (dispatch) => {
        const msg: CommandMessage = {
            command: Command.Overclock,
            params: lookupOverclockLevel(level)
        };

        daemon.next(msg);
        dispatch({ type: SET_OVERCLOCK_LEVEL, level });
    }
}
Example #4
Source File: reducer.ts    From wiregui with MIT License 6 votes vote down vote up
export default function (state = INITIAL_STATE, action: AnyAction) {
  return produce(state, () => {
    switch (action.type) {
      default: {
        break;
      }
    }
  });
}
Example #5
Source File: KliveStore.ts    From kliveide with MIT License 6 votes vote down vote up
/**
   * Replaces the reducer currently used by the store to calculate the state.
   *
   * You might need this if your app implements code splitting and you want to
   * load some of the reducers dynamically. You might also need this if you
   * implement a hot reloading mechanism for Redux.
   *
   * @param nextReducer The reducer for the store to use instead.
   */
  replaceReducer(nextReducer: Reducer<any, AnyAction>): void {
    this.store.replaceReducer(nextReducer);
  }
Example #6
Source File: sequenceReducers.ts    From diagram-maker with Apache License 2.0 6 votes vote down vote up
/**
 * Combine multiple reducers into one that will pipe `state` through the provided reducers one-by-one,
 * passing the result of the previous reducer as an input of the next one.
 *
 * Allows having `null` or `undefined` reducers in the list. They will be treated as identity function and will
 * pass the state forward without any modifications.
 */
export function sequenceReducers<StateType, ActionType extends AnyAction>(
  rootReducer: Reducer<StateType, ActionType>,
  ...reducers: (Reducer<StateType, ActionType> | undefined | null)[]
): Reducer<StateType, ActionType> {
  return (state: StateType | undefined, action: ActionType) => {
    let intermediateState = rootReducer(state, action);
    reducers.forEach((reducer) => {
      if (reducer) {
        intermediateState = reducer(intermediateState, action);
      }
    });
    return intermediateState;
  };
}
Example #7
Source File: loading.ts    From foca with MIT License 6 votes vote down vote up
isLoadingAction = (action: AnyAction): action is LoadingAction => {
  const tester = action as LoadingAction;
  return (
    tester.type === TYPE_SET_LOADING &&
    !!tester.model &&
    !!tester.method &&
    !!tester.payload
  );
}
Example #8
Source File: enqueueSnackbar.tsx    From multisig-react with MIT License 6 votes vote down vote up
enqueueSnackbar = (
  notification: Notification,
  key?: string | number,
  onClick?: () => void,
): ThunkAction<string | number, AppReduxState, undefined, AnyAction> => (dispatch: Dispatch) => {
  key = notification.key || new Date().getTime() + Math.random()

  const newNotification = {
    ...notification,
    key,
    options: {
      ...notification.options,
      onClick,
      // eslint-disable-next-line react/display-name
      action: (actionKey) => (
        <IconButton onClick={() => dispatch(closeSnackbarAction({ key: actionKey }))}>
          <IconClose />
        </IconButton>
      ),
    },
  }

  dispatch(addSnackbar(newNotification))

  return key
}
Example #9
Source File: RawDataConverter.ts    From alchemist with MIT License 6 votes vote down vote up
public static replaceArrayBuffer(obj: ActionDescriptor[]|ActionDescriptor): ActionDescriptor[]|ActionDescriptor {
		const store:Store<CombinedState<{inspector: IInspectorState;}>, AnyAction> = (window as any)._rootStore;
		const settings = getInspectorSettings(store.getState());
		if (!settings.makeRawDataEasyToInspect) {
			return obj;
		}
		rec(obj);
		return obj;

		function rec(data:any) {
			for (const key in data) {
				if (Object.prototype.hasOwnProperty.call(data, key)) {
					if (Array.isArray(data)) {
						for (const item of data) {
							rec(item);
						}
					}
					else if (data[key] instanceof ArrayBuffer) {
						const uint = new Uint8Array(data[key]);
						const arr: number[] = Array.from(uint);

						if (settings.makeRawDataEasyToInspect) {
							data[key] = {
								"_rawData": "alchemistFakeType",
								"_data": arr,
							};							
						} else {
							data[key] = "<ArrayBuffer> This value was ignored for performance reasons. Turn this on in Alchemist > Settings > Support raw data type";
						}
					}
					else if (typeof data[key] === "object") {
						rec(data[key]);
					}
				}				
			}
		}
	}
Example #10
Source File: config.ts    From shadowsocks-electron with GNU General Public License v3.0 6 votes vote down vote up
restoreConfigurationFromFile =
  (info: { success: string, error: { [key: string]: string } }): ThunkAction<void, RootState, unknown, AnyAction> => {
  return (dispatch) => {
    MessageChannel.invoke('main', 'service:desktop', {
      action: 'restoreConfigurationFromFile',
      params: {}
    })
    .then((rsp) => {
      if (rsp.code === 200) {
        dispatch(enqueueSnackbar(info.success, { variant: "success" }));
        dispatch(wipeConfig());
        if (rsp.result.config?.length) {
          rsp.result.config.forEach((conf: Config) => {
            dispatch(addConfig(conf.id, conf))
          });
        }
        if (rsp.result.settings) {
          dispatch(overrideSetting(rsp.result.settings));
        }
      } else {
        dispatch(enqueueSnackbar(info.error[rsp.code] ?? info.error.default, { variant: "warning" }));
      }
    });
  }
}
Example #11
Source File: index.ts    From ui with GNU Affero General Public License v3.0 6 votes vote down vote up
root = (state: State, action: AnyAction): State => {
  switch (action.type) {
    case HYDRATE:
      return { ...state, ...action.payload } as State
  }

  const combined = combineReducers({
    auth,
  })

  return combined(state, action)
}
Example #12
Source File: actions.ts    From pybricks-code with MIT License 6 votes vote down vote up
/**
 * Adds additional members to an action creation function.
 *
 * @param actionCreator The action creation function.
 * @returns actionCreator with type property and match method added.
 */
export function createAction<
    F extends ActionCreationFunction<A>,
    A extends AnyAction = ReturnType<F>,
>(actionCreator: F): Matchable<F, A> {
    // create a default action so we can get the type string.
    const type = actionCreator().type;

    function matches(action: AnyAction): action is ReturnType<F> {
        return action.type === type;
    }

    function when(
        predicate: (action: ReturnType<F>) => boolean,
    ): MatchFunction<ReturnType<F>> {
        return (a: AnyAction): a is ReturnType<F> => {
            if (!matches(a)) {
                return false;
            }

            return predicate(a);
        };
    }

    return Object.assign(actionCreator, <MatchableExtensions<F, A>>{
        toString: () => type,
        matches,
        when,
    });
}
Example #13
Source File: SharedClusters.test.tsx    From rhub-app with MIT License 6 votes vote down vote up
describe('<SharedCluster />', () => {
  let dispatchTracker: AnyAction[] = [];

  beforeAll(() => {
    const mockDispatch = (action: AnyAction) => {
      dispatchTracker.push(action);
    };

    useDispatchMock.mockImplementation(() => mockDispatch);
  });

  afterEach(() => {
    jest.clearAllMocks();
    dispatchTracker = [];
  });

  test('Renders the component', async () => {
    const { result } = connectedRender(<SharedClusters />, mocks.loadedState);

    // dispatches the loadCluster action
    expect(dispatchTracker[0]).toMatchObject({
      type: ClusterTypes.LOAD_REQUEST,
      payload: {
        clusterId: 'all',
      },
    });

    expect(result.queryByText(/^Purpose$/)).toBeInTheDocument();
    expect(result.queryByText(/^How to Use:$/)).toBeInTheDocument();
    expect(
      result.queryByText(/^Naming Convention Examples:$/)
    ).toBeInTheDocument();

    // Renders the ClusterView component with clusterViewType='shared'
    expect(result.queryByText(/^Shared Clusters$/)).toBeInTheDocument();
  });
});
Example #14
Source File: BulkReducer.ts    From Protoman with MIT License 6 votes vote down vote up
export default function BulkReducer(s: AppState, action: AnyAction): AppState {
  if (BulkActionTypes.includes(action.type)) {
    const a = action as BulkAction;

    switch (a.type) {
      case 'IMPORT_COLLECTION':
        return produce(s, draft => {
          const names = s.collections.map(([name]) => name);
          const prefix = 'Imported';
          let idx = 1;
          while (names.includes(prefix + idx)) idx++;
          console.log(a.collection);
          draft.collections.push([prefix + idx, a.collection as Draft<Collection>]);
        });
      default:
        return s;
    }
  }

  return s;
}
Example #15
Source File: counter.spec.ts    From memex with MIT License 6 votes vote down vote up
describe('reducers', () => {
  describe('counter', () => {
    it('should handle initial state', () => {
      expect(counterReducer(undefined, {} as AnyAction)).toMatchSnapshot();
    });

    it('should handle INCREMENT_COUNTER', () => {
      expect(
        counterReducer({ value: 1 }, { type: increment })
      ).toMatchSnapshot();
    });

    it('should handle DECREMENT_COUNTER', () => {
      expect(
        counterReducer({ value: 1 }, { type: decrement })
      ).toMatchSnapshot();
    });

    it('should handle unknown action type', () => {
      expect(
        counterReducer({ value: 1 }, { type: 'unknown' })
      ).toMatchSnapshot();
    });
  });
});
Example #16
Source File: application.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
toggleLogActionsMiddleware: Middleware<{}, StoreState> = (store: MiddlewareAPI<Dispatch, StoreState>) => (
  next: Dispatch
) => (action: AnyAction) => {
  const isLogActionsAction = action.type === toggleLogActions.type;
  if (isLogActionsAction) {
    return next(action);
  }

  const logActionsTrue =
    window && window.location && window.location.search && window.location.search.indexOf('logActions=true') !== -1;
  const logActionsFalse =
    window && window.location && window.location.search && window.location.search.indexOf('logActions=false') !== -1;
  const logActions = store.getState().application.logActions;

  if (logActionsTrue && !logActions) {
    store.dispatch(toggleLogActions());
  }

  if (logActionsFalse && logActions) {
    store.dispatch(toggleLogActions());
  }

  return next(action);
}
Example #17
Source File: dispatch.ts    From reactant with MIT License 6 votes vote down vote up
dispatch = <T extends AnyAction = AnyAction>(
  target: ThisService,
  action: T
) => {
  // the api should not be implemented as a decorator
  // (because it should return new state should get a the current new state, low performance.)
  if (target[storeKey]) {
    target[storeKey]!.dispatch(action);
  } else {
    throw new Error(
      `Store for '${target.constructor.name}' service does not exist, and make sure you have set any Redux state.`
    );
  }
}
Example #18
Source File: FSReducer.ts    From UsTaxes with GNU Affero General Public License v3.0 6 votes vote down vote up
fsReducer = <S extends USTState, A extends AnyAction>(
  filename: string,
  reducer: Reducer<S, A>
): Reducer<S, A & PersistActions> => {
  return (state: S | undefined, action: A & PersistActions): S => {
    const newState = reducer(state, action)

    switch (action.type) {
      case 'fs/recover': {
        // we know now that the action is a FSRecover,
        // so we can safely cast it to a FSRecover<USTSerializedState>.
        return {
          ...newState,
          ...migrateAgeAndBlindness(
            migrateEachYear(
              // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
              stringToState(action.data)
            )
          )
        } as S // migrations return any, must coerce.
      }
      case 'fs/persist': {
        download(filename, stateToString(newState))
        return newState
      }
      default: {
        return newState
      }
    }
  }
}
Example #19
Source File: app.ts    From marina with MIT License 6 votes vote down vote up
export function logIn(password: Password, passwordHash: PasswordHash): AnyAction {
  try {
    if (!match(password, passwordHash)) {
      return {
        type: AUTHENTICATION_FAILURE,
        payload: { error: new Error(INVALID_PASSWORD_ERROR) },
      };
    }

    return { type: AUTHENTICATION_SUCCESS };
  } catch (error) {
    return { type: AUTHENTICATION_FAILURE, payload: { error } };
  }
}
Example #20
Source File: index.d.ts    From shippo with MIT License 5 votes vote down vote up
createStore: (compose?: ((...middleware: Middleware[]) => StoreEnhancer) | undefined) => {
    stores: import("redux").Store<import("redux").EmptyObject & {
        user: import("./user/user-reducer").IUserStore;
    }, import("@kazura/react-store").StoreAction<import("./user/user-reducer").IUserStore>>;
    thunkDispatch: ThunkDispatch<AnyAction>;
    dispatch: Dispatch<AnyAction>;
    selector: <T>(selector: (store: IStores) => T) => T;
}
Example #21
Source File: newsletter-reducer.ts    From pola-web with MIT License 5 votes vote down vote up
newsletterReducer: Reducer<ISubscribeState, AnyAction> = (
  state: ISubscribeState = initialState,
  action: IAction
) => {
  const reducer: any = reducers[action.type];
  return reducer ? reducer(state, action) : state;
}