redux#Action TypeScript Examples

The following examples show how to use redux#Action. 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: buyVIP.ts    From client with MIT License 6 votes vote down vote up
buyVIP: ActionCreator<ThunkAction<void, AppState, any, Action>> = (
  vipDays: number
) => async dispatch => {
  dispatch({ type: SET_ACCOUNT_LOADER, payload: true });

  try {
    const { data } = await axios.patch(
      process.env.REACT_APP_API_URI + '/user/account/vip',
      {
        vipDays
      }
    );

    dispatch({ type: SET_ACCOUNT_INFO, payload: data.info });

    dispatch({ type: SET_CREDITS, payload: data.credits });

    notice(data);
  } catch (error) {
    notice(error);
  }

  dispatch({ type: SET_ACCOUNT_LOADER, payload: false });
}
Example #4
Source File: store.ts    From rn-clean-architecture-template with MIT License 6 votes vote down vote up
export function configureStore(): StoreContainer {
  const reducerManager = createReducerManager({
    authentication: authenticationReducer,
    configuration: configurationReducer,
  });
  const {rootEpic, epicMiddleware, epic$, addEpic} = createEpicManager(
    {},
    authenticationEpic,
    configurationEpic,
  );
  // Create a store with the root reducer function being the one exposed by the manager.

  const action$ = new BehaviorSubject<Action>({type: 'init'});
  const reducer = (
    state: RootStoreState | undefined,
    action: Action<string>,
  ) => {
    action$.next(action);
    return reducerManager.reduce(state, action);
  };
  const store = createStore<RootStoreState, Action<string>, any, any>(
    reducer,
    applyMiddleware(epicMiddleware),
  );
  epicMiddleware.run(rootEpic);

  // Optional: Put the reducer manager on the store so it is easily accessible
  return {
    reducerManager,
    store,
    epic$,
    action$,
    addEpic,
  };
}
Example #5
Source File: moveItem.ts    From client with MIT License 6 votes vote down vote up
moveItem: ActionCreator<ThunkAction<
  Promise<any>,
  AppState,
  any,
  Action
>> = ({ itemSlot, newSlot, from, to }) => async dispatch => {
  dispatch({ type: SET_EXTRA_LOADER, payload: true });

  try {
    if (from !== to || (from === to && from !== 'storage')) {
      const { data } = await axios.patch(
        process.env.REACT_APP_API_URI + '/user/extra/storage/moveitem',
        {
          itemSlot,
          newSlot,
          from,
          to
        }
      );

      dispatch({ type: WAREHOUSE_UPDATE, payload: data.warehouse });
      dispatch({ type: STORAGE_UPDATE, payload: data.storage });
    }
  } catch (error) {
    notice(error);
  }

  dispatch({ type: SET_EXTRA_LOADER, payload: false });
}
Example #6
Source File: Checkout.container.tsx    From react-native-woocommerce with MIT License 6 votes vote down vote up
CheckoutContainer = (props: CartState): JSX.Element => {
  const products = useSelector(selectors.cart.getProducts);
  const total = useSelector(selectors.cart.getTotal);
  const dispatch = useDispatch();

  const handleCheckoutSubmit = (userInfo: object): Action => {
    const order = {
      billing: userInfo,
      shipping: userInfo,
      line_items: products.map(({ id, quantity }: CartItem) => ({
        product_id: id,
        quantity
      }))
    };

    return dispatch(actions.checkoutCommand(order));
  };

  return (
    <Checkout
      {...props}
      handleCheckoutSubmit={handleCheckoutSubmit}
      products={products}
      total={total}
    />
  );
}
Example #7
Source File: changePassword.ts    From client with MIT License 6 votes vote down vote up
changePassword: ActionCreator<ThunkAction<
  void,
  AppState,
  any,
  Action
>> = (form: Form) => async dispatch => {
  dispatch({ type: SET_ACCOUNT_LOADER, payload: true });

  try {
    const { data } = await axios.patch(
      process.env.REACT_APP_API_URI + '/user/account/password',
      form
    );

    notice(data);
  } catch (error) {
    notice(error);
  }

  dispatch({ type: SET_ACCOUNT_LOADER, payload: false });
}
Example #8
Source File: InfrastructureNamespace.ts    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
reducer: Reducer<State> = (state: State | undefined, incomingAction: Action): State => {
  if (state === undefined) {
    return unloadedState;
  }

  const action = incomingAction as KnownAction;
  switch (action.type) {
    case 'REQUEST_NAMESPACES':
      return Object.assign({}, state, {
        isLoading: true,
      });
    case 'RECEIVE_NAMESPACES':
      return Object.assign({}, state, {
        namespaces: action.namespaces,
      });
    default:
      return state;
  }
}
Example #9
Source File: DiagramMaker.ts    From diagram-maker with Apache License 2.0 6 votes vote down vote up
constructor(
    domHandle: string | HTMLElement,
    config: DiagramMakerConfig<NodeType, EdgeType>,
    {
      initialData, consumerRootReducer, consumerEnhancer, eventListener,
    }: {
      initialData?: DiagramMakerData<NodeType, EdgeType>,
      consumerRootReducer?: Reducer<DiagramMakerData<NodeType, EdgeType>, Action>,
      consumerEnhancer?: StoreEnhancer,
      eventListener?: ObserverCallback;
    } = {},
  ) {
    this.config = new ConfigService(config);
    this.store = createStore(initialData, consumerRootReducer, consumerEnhancer, this.config.getActionInterceptor());
    this.api = new DiagramMakerApi(this.store);

    this.container = DiagramMaker.getContainer(domHandle);
    this.observer = new Observer();
    if (eventListener) {
      this.observer.subscribeAll(eventListener);
    }
    this.eventManager = new UIEventManager(this.observer, this.container);
    this.actionDispatcher = new ActionDispatcher(this.observer, this.store, this.config);

    render<NodeType, EdgeType>(this.store, this.container, this.config);

    this.updateContainer();
  }
Example #10
Source File: actions.ts    From pybricks-code with MIT License 6 votes vote down vote up
function didFailToConnectCreator(
    reason: BootloaderConnectionFailureReason,
    arg1?: Error,
): Action<typeof didFailToConnectType> & {
    reason: BootloaderConnectionFailureReason;
    err?: Error;
} {
    if (reason === BootloaderConnectionFailureReason.Unknown) {
        return {
            type: didFailToConnectType,
            reason,
            err: arg1,
        };
    }

    return { type: didFailToConnectType, reason };
}
Example #11
Source File: verification.ts    From client with MIT License 6 votes vote down vote up
userVerification: ActionCreator<ThunkAction<
  Promise<any>,
  AppState,
  any,
  Action
>> = () => async dispatch => {
  try {
    if (localStorage.nyxToken) {
      const { data } = await axios.post(
        process.env.REACT_APP_API_URI + '/user/account/verify'
      );

      dispatch({
        type: LOGIN,
        payload: data
      });
    } else {
      dispatch({
        type: LOGIN_FAILED
      });
    }
  } catch (error) {
    dispatch({
      type: LOGOUT
    });

    dispatch({
      type: LOGIN_FAILED
    });
  }
}
Example #12
Source File: index.spec.tsx    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
jest.mock('../../../../store/InfrastructureNamespace', () => {
  return {
    actionCreators: {
      requestNamespaces: (): AppThunk<Action, Promise<void>> => async (dispatch): Promise<void> => {
        return Promise.resolve();
      }
    } as InfrastructureNamespaceStore.ActionCreators,
  };
});
Example #13
Source File: logout.ts    From client with MIT License 6 votes vote down vote up
userLogout: ActionCreator<ThunkAction<void, AppState, any, Action>> = (
  history: any
) => dispatch => {
  delete localStorage.nyxToken;

  dispatch({
    type: LOGOUT
  });

  history.push('/');
}
Example #14
Source File: FactoryResolver.ts    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
reducer: Reducer<State> = (state: State | undefined, incomingAction: Action): State => {
  if (state === undefined) {
    return unloadedState;
  }

  const action = incomingAction as KnownAction;
  switch (action.type) {
    case 'REQUEST_FACTORY_RESOLVER':
      return Object.assign({}, state, {
        isLoading: true,
      });
    case 'RECEIVE_FACTORY_RESOLVER':
      return Object.assign({}, state, {
        resolver: action.resolver,
      });
    default:
      return state;
  }
}
Example #15
Source File: MainProcessMiddleware.ts    From YoutubeLiveApp with MIT License 6 votes vote down vote up
export default function MainProcessMiddleware(): Middleware {
  return (store) => (next) => (action: Action) => {
    // イベントリスナが未登録なら登録する
    if (!ipcMain.eventNames().some((name) => name === IPCEvent.InitialState.CHANNEL_NAME_FROM_PRELOAD)) {
      // state の初期値要求
      ipcMain.on(IPCEvent.InitialState.CHANNEL_NAME_FROM_PRELOAD, (event) => {
        const state = store.getState();
        event.sender.send(IPCEvent.StateChanged.CHANNEL_NAME_FROM_MAIN, {
          type: IPCEvent.InitialState.CHANNEL_NAME_FROM_MAIN,
          payload: state,
        });
      });
    }
    // イベントリスナが未登録なら登録する
    if (!ipcMain.eventNames().some((name) => name === IPCEvent.StateChanged.CHANNEL_NAME_FROM_PRELOAD)) {
      ipcMain.on(IPCEvent.StateChanged.CHANNEL_NAME_FROM_PRELOAD, (event, action: Action) => {
        console.log({ MainProcessMiddleWare: action });
        App.childWindows.forEach(
          (value) => event.sender != value.webContents && value.webContents.send(IPCEvent.StateChanged.CHANNEL_NAME_FROM_MAIN, action)
        );
        next(action);
      });
    }

    next(action);
    App.childWindows.forEach((value) => value.webContents.send(IPCEvent.StateChanged.CHANNEL_NAME_FROM_MAIN, action));
    console.log({ action });
  };
}
Example #16
Source File: login.ts    From client with MIT License 6 votes vote down vote up
userLogin: ActionCreator<ThunkAction<
  Promise<any>,
  AppState,
  any,
  Action
>> = ({ username, password }, history) => async dispatch => {
  dispatch({ type: SET_LOGIN_LOADER, payload: true });

  try {
    const { data } = await axios.post(
      process.env.REACT_APP_API_URI + '/user/account/auth',
      { username, password }
    );

    localStorage.nyxToken = data.jwt_token;
    axios.defaults.headers.common.nyxAuthToken = data.jwt_token;

    dispatch({ type: LOGIN, payload: data });
    notice(data);

    if (!window.location.pathname.includes('/user/')) {
      history.push('/user/account/logs');
    }
  } catch (error) {
    dispatch({ type: LOGIN_FAILED });
    notice(error);
  }

  dispatch({ type: SET_LOGIN_LOADER, payload: false });
}
Example #17
Source File: Cart.container.tsx    From RNWCShop with GNU General Public License v3.0 6 votes vote down vote up
CartContainer = ({ navigation }: Props): JSX.Element => {
  const products = useSelector((state: CartState) => state.products || []);
  const total = useSelector((state: CartState) => state.total || 0);
  const dispatch = useDispatch();

  const handlers = {
    handleProductPress: (id: number): void =>
      navigation.navigate('Detail', { id }),
    handleCheckoutPress: (): void => navigation.navigate('Checkout'),
    addToCart: (product: Product): Action =>
      dispatch(actions.addToCart(product)),
    removeFromCart: (productId: number): Action =>
      dispatch(actions.removeFromCart(productId)),
    addQuantity: (productId: number): Action =>
      dispatch(actions.addQuantity(productId)),
    subQuantity: (productId: number): Action =>
      dispatch(actions.subQuantity(productId)),
    resetCart: (): Action => dispatch(actions.resetCart())
  };

  return <Cart {...handlers} products={products} total={total} />;
}
Example #18
Source File: Browse.container.tsx    From react-native-woocommerce with MIT License 6 votes vote down vote up
BrowseContainer = (props: ProductsState): JSX.Element => {
  const products = useSelector(selectors.products.getProducts);
  const refreshing = useSelector(selectors.products.isRefreshing);
  const page = useSelector(selectors.products.getPage);
  const dispatch = useDispatch();
  const navigation = useNavigation();

  const handlers = {
    onRefresh: (): Action => dispatch(actions.refetchProducts({ page })),
    onEndReached: (): Action => dispatch(actions.productsEndReached({ page })),
    handleProductPress: (id: number): void => navigation.navigate(Routes.Product, { id }),
    addToCart: (product: Product): Action => {
      navigation.navigate(Routes.Orders, { screen: Routes.Cart });

      return dispatch(cartActions.addToCart(product));
    },
    removeFromCart: (productId: number): Action => dispatch(cartActions.removeFromCart(productId)),
    addQuantity: (productId: number): Action => dispatch(cartActions.addQuantity(productId)),
    subQuantity: (productId: number): Action => dispatch(cartActions.subQuantity(productId))
  };

  useEffect(() => {
    dispatch(actions.productsQuery({ page }));
  }, []);

  return (
    <Browse
      {...props}
      {...handlers}
      products={products}
      refreshing={refreshing}
      page={page}
    />
  );
}
Example #19
Source File: withdraw.ts    From client with MIT License 6 votes vote down vote up
depositResources: ActionCreator<ThunkAction<
  Promise<any>,
  AppState,
  any,
  Action
>> = (resources: Resource[]) => async dispatch => {
  dispatch({ type: SET_EXTRA_LOADER, payload: true });

  try {
    const { data } = await axios.patch(
      process.env.REACT_APP_API_URI + '/user/extra/resources/withdraw',
      { withdraws: resources }
    );

    const updated: any = {
      ...data.resources,
      list: data.resources.resources
    };
    delete updated.resources;

    dispatch({ type: WAREHOUSE_UPDATE, payload: data.items });
    dispatch({ type: RESOURCES_UPDATE, payload: updated });
    notice(data);
  } catch (error) {
    notice(error);
  }

  dispatch({ type: SET_EXTRA_LOADER, payload: false });
}
Example #20
Source File: user-async-action.ts    From shippo with MIT License 5 votes vote down vote up
asyncAction = createAsyncAction<IStores, undefined, Action<string>>()
Example #21
Source File: sentryMiddleware.ts    From react-native-template with MIT License 5 votes vote down vote up
sentryMiddleware = () => (next: any) => (action: Action<string>) => {
  action.type &&
    Sentry.addBreadcrumb({
      category: action.type
    })

  return next(action)
}
Example #22
Source File: LeaveComments.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
mapDispatchToProps = (
  dispatch: Dispatch<Action>,
  ownProps: LeaveCommentsProps,
) => ({
  changeEmployeeLeaveRequestStatus:
    ownProps.route.params.changeEmployeeLeaveRequestStatusAction,
  dispatch,
})
Example #23
Source File: createState.ts    From reactant with MIT License 5 votes vote down vote up
/**
 * ## Description
 *
 * It allows a class state to be defined with a reducer,
 * which is often used in situations where a class state is being migrated from the Redux boilerplate code to the Reactant.
 * And it's often used in conjunction with `dispatch()`.
 *
 * ## Example
 *
 * ```ts
 * const type = 'count_increase';
 *
 * interface CountAction {
 *  type: typeof type;
 *  state: number;
 * }
 *
 * @injectable()
 * class Counter {
 *  @state
 *  count = createState<CountAction['state'], CountAction>(
 *    ($state = 0, $action) => ($action.type === type ? $action.state : $state)
 *  );
 *
 *  increase() {
 *    dispatch<CountAction>(this, {
 *      type,
 *      state: this.count + 1,
 *    });
 *  }
 * }
 *
 * const app = createApp({
 *   modules: [],
 *   main: Counter,
 *   render: () => {},
 * });
 *
 * app.instance.increase();
 * expect(app.instance.count).toBe(1);
 * ```
 */
export function createState<S = any, A extends Action = AnyAction>(
  reducer: Reducer<S, A>
): S {
  return reducer as any;
}
Example #24
Source File: clearCharacters.ts    From client with MIT License 5 votes vote down vote up
clearCharacters: ActionCreator<ThunkAction<
  void,
  AppState,
  any,
  Action
>> = () => dispatch => {
  dispatch({ type: CLEAR_RANK_CHARACTERS });
}
Example #25
Source File: createAuspiceState.ts    From nextclade with MIT License 5 votes vote down vote up
export function createAuspiceState<A extends Action = AnyAction>(json: AuspiceJsonV2, dispatch: Dispatch<A>) {
  return createStateFromQueryOrJSONs({ json: copy(json), query: {}, dispatch })
}
Example #26
Source File: epic.ts    From rn-clean-architecture-template with MIT License 5 votes vote down vote up
export function createEpicManager(
  dependencies: RootEpicDependency = {},
  ...epics: Epic[]
): {
  addEpic: (epic: Epic) => void;
  epic$: BehaviorSubject<Epic>;
  rootEpic: RootEpic;
  epicMiddleware: EpicMiddleware<
    Action,
    Action,
    RootStoreState,
    RootEpicDependency
  >;
} {
  const addedEpics: Epic[] = [];
  const epic$ = new BehaviorSubject(combineEpics(...epics));
  const addEpic = (epic: Epic) => {
    if (addedEpics.includes(epic)) {
      return;
    }
    addedEpics.push(epic);
    epic$.next(epic);
  };
  const rootEpic: Epic = (action$, state$) =>
    epic$.pipe(
      mergeMap((epic) =>
        epic(action$, state$, dependencies).pipe(
          catchError((_, source) => source),
        ),
      ),
    );

  const epicMiddleware = createEpicMiddleware<
    Action,
    Action,
    RootStoreState,
    RootEpicDependency
  >();
  return {epic$, rootEpic, epicMiddleware, addEpic};
}
Example #27
Source File: removeLocalSafe.ts    From multisig-react with MIT License 5 votes vote down vote up
removeLocalSafe = (safeAddress: string) => async (dispatch: Dispatch): Promise<Action | void> => {
  const storedSafes = await loadStoredSafes()
  if (storedSafes) {
    delete storedSafes[safeAddress]
  }
  dispatch(removeSafe(safeAddress))
}
Example #28
Source File: index.ts    From che-dashboard-next with Eclipse Public License 2.0 5 votes vote down vote up
reducer: Reducer<State> = (state: State | undefined, incomingAction: Action): State => {
  if (state === undefined) {
    return unloadedState;
  }

  const action = incomingAction as KnownAction;
  switch (action.type) {
    case 'REQUEST_METADATA':
    case 'REQUEST_SCHEMA':
    case 'REQUEST_DEVFILE':
      return createState(state, {
        isLoading: true,
      });
    case 'RECEIVE_METADATA':
      return createState(state, {
        isLoading: false,
        metadata: action.metadata,
      });
    case 'RECEIVE_DEVFILE':
      return createState(state, {
        isLoading: false,
        devfiles: {
          [action.url]: {
            content: action.devfile,
          }
        }
      });
    case 'RECEIVE_SCHEMA':
      return createState(state, {
        isLoading: false,
        schema: action.schema,
      });
    case 'SET_FILTER': {
      return createState(state, {
        filter: action.value,
      });
    }
    case 'CLEAR_FILTER': {
      return createState(state, {
        filter: '',
      });
    }
    default:
      return state;
  }

}
Example #29
Source File: redux-undo-redo.d.ts    From diagram-maker with Apache License 2.0 5 votes vote down vote up
export declare function undoHistoryReducer<ActionType extends Action>(
  state: UndoHistoryState<ActionType> | undefined, action: AnyAction
): UndoHistoryState<ActionType>;