redux#Reducer TypeScript Examples

The following examples show how to use redux#Reducer. 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: handlePlugin.ts    From reactant with MIT License 7 votes vote down vote up
handlePlugin: HandlePlugin = (
  service: any,
  pluginHooks: PluginHooks
) => {
  if (service instanceof PluginModule) {
    if (typeof service.beforeCombineRootReducers === 'function') {
      pluginHooks.beforeCombineRootReducers.push(
        (reducers: ReducersMapObject) =>
          service.beforeCombineRootReducers!(reducers)
      );
    }
    if (typeof service.afterCombineRootReducers === 'function') {
      pluginHooks.afterCombineRootReducers.push((rootReducer: Reducer) =>
        service.afterCombineRootReducers!(rootReducer)
      );
    }
    if (typeof service.preloadedStateHandler === 'function') {
      pluginHooks.preloadedStateHandler.push(
        (preloadedState: PreloadedState<any>) =>
          service.preloadedStateHandler!(preloadedState)
      );
    }
    if (typeof service.enhancer === 'function') {
      pluginHooks.enhancer.push(service.enhancer.bind(service));
    }
    if (typeof service.middleware === 'function') {
      pluginHooks.middleware.push(service.middleware.bind(service));
    }
    if (typeof service.afterCreateStore === 'function') {
      pluginHooks.afterCreateStore.push(service.afterCreateStore.bind(service));
    }
    if (typeof service.provider === 'function') {
      pluginHooks.provider.push(service.provider.bind(service));
    }
  }
}
Example #2
Source File: reducers.ts    From pybricks-code with MIT License 6 votes vote down vote up
checkingForUpdate: Reducer<boolean> = (state = false, action) => {
    if (appCheckForUpdate.matches(action)) {
        return true;
    }

    if (appDidCheckForUpdate.matches(action)) {
        if (!action.updateFound) {
            return false;
        }
        // otherwise we wait for service worker to download everything
        return state;
    }

    if (serviceWorkerDidUpdate.matches(action)) {
        return false;
    }

    return state;
}
Example #3
Source File: reducer.ts    From slice-machine with Apache License 2.0 6 votes vote down vote up
createReducer = (): Reducer =>
  combineReducers({
    modal: modalReducer,
    loading: loadingReducer,
    userContext: userContextReducer,
    environment: environmentReducer,
    simulator: simulatorReducer,
    availableCustomTypes: availableCustomTypesReducer,
    selectedCustomType: selectedCustomTypeReducer,
    slices: slicesReducer,
    router: routerReducer,
  })
Example #4
Source File: reducers.ts    From pybricks-code with MIT License 6 votes vote down vote up
hasUnresolvedInstallPrompt: Reducer<boolean> = (state = false, action) => {
    if (appDidReceiveBeforeInstallPrompt.matches(action)) {
        return true;
    }

    if (didInstall.matches(action)) {
        return false;
    }

    return state;
}
Example #5
Source File: index.ts    From rhub-app with MIT License 6 votes vote down vote up
reducer: Reducer<CowsayState> = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case CowsayTypes.LOAD_REQUEST:
      return { ...state, loading: true };
    case CowsayTypes.LOAD_SUCCESS:
      return {
        loading: false,
        error: false,
        message: action.payload,
      };
    case CowsayTypes.LOAD_FAILURE:
      return { loading: false, error: true, message: '' };
    default:
      return state;
  }
}
Example #6
Source File: reducer.ts    From roam-toolkit with MIT License 6 votes vote down vote up
settings: Reducer<IAppSettings, SettingsActions> = (state = initialState, action) => {
    const {payload} = action
    switch (action.type) {
        case 'RETURN_TO_HOME':
            return {...state, featureId: ''}

        case 'SET_FEATURE_ID':
            return {...state, featureId: payload}

        default:
            return state
    }
}
Example #7
Source File: storage.tsx    From reactant with MIT License 6 votes vote down vote up
afterCombineRootReducers(rootReducer: Reducer) {
    return persistReducer(
      {
        blacklist: [...Object.keys(this.persistConfig), ...this.blacklist],
        ...this.persistRootConfig,
      },
      rootReducer
    );
  }
Example #8
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 #9
Source File: index.ts    From marina with MIT License 6 votes vote down vote up
// custom persist reducer function
function persist<S extends any>(opts: {
  reducer: Reducer<S, AnyAction>;
  migrate: PersistMigrate;
  key: string;
  whitelist?: string[];
  blacklist?: string[];
  version?: number;
}): Reducer<S & PersistPartial, AnyAction> {
  return persistReducer(
    createLocalStorageConfig(opts.key, opts.migrate, opts.whitelist, opts.blacklist, opts.version),
    opts.reducer
  );
}
Example #10
Source File: reducer.ts    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
counterReducer: Reducer<CounterState, CounterAction> = (
  state: CounterState = initialState,
  action: CounterAction,
): CounterState => {
  switch (action.type) {
    case Type.ADD:
      return {
        ...state,
        count: state.count + (action.amount || 0),
      };
    case Type.DECREMENT:
      return {
        ...state,
        count: state.count - 1,
      };
    case Type.INCREMENT:
      return {
        ...state,
        count: state.count + 1,
      };
    default: {
      const _: never = action.type;

      return state;
    }
  }
}
Example #11
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 #12
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 #13
Source File: Branding.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 KnownActions;
  switch (action.type) {
    case 'REQUEST_BRANDING':
      return Object.assign({}, state, {
        isLoading: true,
      });
    case 'RECEIVED_BRANDING':
      return Object.assign({}, state, {
        isLoading: false,
        data: action.data,
      });
    default:
      return state;
  }
}
Example #14
Source File: rootReducer.ts    From nosgestesclimat-site with MIT License 6 votes vote down vote up
mainReducer = (state: any, action: Action) =>
	combineReducers({
		explainedVariable,
		// We need to access the `rules` in the simulation reducer
		simulation: (a: Simulation | null = null, b: Action): Simulation | null =>
			simulation(a, b),
		previousSimulation: defaultTo(null) as Reducer<SavedSimulation | null>,
		situationBranch,
		rules,
		actionChoices,
		conference,
		survey,
		iframeOptions: defaultTo(null),
		tutorials,
		storedTrajets,
		thenRedirectTo,
		tracking,
	})(state, action)
Example #15
Source File: PersistManager.ts    From foca with MIT License 6 votes vote down vote up
combineReducer(original: Reducer): Reducer<Record<string, object>> {
    return (state, action) => {
      if (state === void 0) state = {};

      if (isHydrateAction(action)) {
        return Object.assign({}, state, freezeState(action.payload));
      }

      return original(state, action);
    };
  }
Example #16
Source File: index.ts    From slice-machine with Apache License 2.0 6 votes vote down vote up
availableCustomTypesReducer: Reducer<
  AvailableCustomTypesStoreType | null,
  CustomTypesActions
> = (state, action) => {
  if (!state) return null;

  switch (action.type) {
    case getType(refreshStateCreator): {
      const normalizedNewCustomType = normalizeFrontendCustomTypes(
        action.payload.localCustomTypes,
        action.payload.remoteCustomTypes
      );

      return {
        ...state,
        ...normalizedNewCustomType,
      };
    }
    case getType(createCustomTypeCreator.success): {
      const normalizedNewCustomType = normalizeFrontendCustomType(
        action.payload.newCustomType
      );

      return {
        ...state,
        ...normalizedNewCustomType,
      };
    }
    default:
      return state;
  }
}
Example #17
Source File: withHotRedux.hoc.tsx    From rn-clean-architecture-template with MIT License 6 votes vote down vote up
withHotRedux = (
  reducerKey: string,
  reducer: Reducer,
  epic: Epic,
) => (Component: React.FC<any> | React.ComponentType): React.ComponentType => {
  return class WithHotRedux extends React.PureComponent {
    constructor(props: any) {
      super(props);
      const {reducerManager, addEpic} = container.resolve<StoreContainer>(
        AppDependencies.StoreContainer,
      );
      reducerManager.add(reducerKey, reducer);
      addEpic(epic);
    }
    render() {
      return <Component {...this.props} />;
    }
  };
}
Example #18
Source File: reducers.ts    From pybricks-code with MIT License 5 votes vote down vote up
runtime: Reducer<HubRuntimeState> = (
    state = HubRuntimeState.Disconnected,
    action,
) => {
    if (didConnect.matches(action)) {
        return HubRuntimeState.Unknown;
    }

    if (didDisconnect.matches(action)) {
        return HubRuntimeState.Disconnected;
    }

    if (didStartDownload.matches(action)) {
        // disconnected overrides download
        if (state === HubRuntimeState.Disconnected) {
            return state;
        }
        return HubRuntimeState.Loading;
    }

    if (didFinishDownload.matches(action)) {
        // disconnected overrides download
        if (state === HubRuntimeState.Disconnected) {
            return state;
        }
        return HubRuntimeState.Loaded;
    }

    if (didFailToFinishDownload.matches(action)) {
        // disconnected overrides download
        if (state === HubRuntimeState.Disconnected) {
            return state;
        }
        return HubRuntimeState.Idle;
    }

    if (didReceiveStatusReport.matches(action)) {
        // The loading state is determined solely by the IDE, so we can't
        // let the hub status interfere with it.
        if (
            state === HubRuntimeState.Disconnected ||
            state === HubRuntimeState.Loading
        ) {
            return state;
        }

        if (action.statusFlags & statusToFlag(Status.UserProgramRunning)) {
            return HubRuntimeState.Running;
        }

        return HubRuntimeState.Idle;
    }

    return state;
}
Example #19
Source File: modelStore.ts    From foca with MIT License 5 votes vote down vote up
protected consumers: Record<string, Reducer> = {};
Example #20
Source File: index.ts    From ui with GNU Affero General Public License v3.0 5 votes vote down vote up
auth: Reducer<AuthState, Action> = (state = initialState): AuthState => {
  return state
}
Example #21
Source File: index.ts    From rhub-app with MIT License 5 votes vote down vote up
reducer: Reducer<LabLocationState> = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case LabLocationTypes.LOAD_REQUEST:
      return {
        ...state,
        loading: true,
        error: false,
        errMsg: {},
      };
    case LabLocationTypes.CREATE_REQUEST:
    case LabLocationTypes.DELETE_REQUEST:
    case LabLocationTypes.UPDATE_REQUEST:
      return {
        ...state,
        loading: true,
        error: false,
        errMsg: {},
      };
    case LabLocationTypes.LOAD_SUCCESS: {
      if (action.payload.locationId === 'all') {
        const policies = action.payload.data;
        return {
          ...state,
          loading: false,
          error: false,
          data: policies.reduce(LabLocationToState, state.data),
        };
      }
      return {
        ...state,
        loading: false,
        error: false,
        data: LabLocationToState(state.data, action.payload.data),
      };
    }
    case LabLocationTypes.CREATE_SUCCESS:
    case LabLocationTypes.UPDATE_SUCCESS:
      return { ...state, loading: false, error: false };
    case LabLocationTypes.DELETE_SUCCESS:
      const { data } = state;
      const { locationId } = action.payload;
      delete data[locationId];
      return {
        ...state,
        loading: false,
        error: false,
        data,
      };
    case LabLocationTypes.LOAD_FAILURE:
    case LabLocationTypes.CREATE_FAILURE:
    case LabLocationTypes.DELETE_FAILURE:
    case LabLocationTypes.UPDATE_FAILURE:
      return {
        ...state,
        errMsg: action.payload,
        loading: false,
        error: true,
      };
    default:
      return state;
  }
}
Example #22
Source File: reducerTester.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
reducerTester = <State>(): Given<State> => {
  let reducerUnderTest: Reducer<State, PayloadAction<any>>;
  let resultingState: State;
  let initialState: State;
  let showDebugOutput = false;

  const givenReducer = (
    reducer: Reducer<State, PayloadAction<any>>,
    state: State,
    debug = false,
    disableDeepFreeze = false
  ): When<State> => {
    reducerUnderTest = reducer;
    initialState = { ...state };
    if (!disableDeepFreeze) {
      initialState = deepFreeze(initialState);
    }
    showDebugOutput = debug;

    return instance;
  };

  const whenActionIsDispatched = (action: PayloadAction<any>): Then<State> => {
    resultingState = reducerUnderTest(resultingState || initialState, action);

    return instance;
  };

  const thenStateShouldEqual = (state: State): When<State> => {
    if (showDebugOutput) {
      console.log(JSON.stringify(resultingState, null, 2));
    }
    expect(resultingState).toEqual(state);

    return instance;
  };

  const thenStatePredicateShouldEqual = (predicate: (resultingState: State) => boolean): When<State> => {
    if (showDebugOutput) {
      console.log(JSON.stringify(resultingState, null, 2));
    }
    expect(predicate(resultingState)).toBe(true);

    return instance;
  };

  const instance: ReducerTester<State> = {
    thenStateShouldEqual,
    thenStatePredicateShouldEqual,
    givenReducer,
    whenActionIsDispatched,
  };

  return instance;
}
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: search-reducer.ts    From pola-web with MIT License 5 votes vote down vote up
searchReducer: Reducer<SearchState, AnyAction> = (state: SearchState = initialState, action: IAction) => {
  const reducer: any = reducers[action.type];
  return reducer ? reducer(state, action) : state;
}
Example #25
Source File: plugin.ts    From reactant with MIT License 5 votes vote down vote up
/** As hook after combine rootReducers */
  afterCombineRootReducers?(rootReducer: Reducer): Reducer;
Example #26
Source File: friends-reducer.ts    From pola-web with MIT License 5 votes vote down vote up
friendsReducer: Reducer<IFriendsState, AnyAction> = (
  state: IFriendsState = initialState,
  action: IAction
) => {
  const reducer: any = reducers[action.type];
  return reducer ? reducer(state, action) : state;
}
Example #27
Source File: reducers.ts    From pybricks-code with MIT License 5 votes vote down vote up
fileName: Reducer<string> = (state = '', action) => {
    if (deleteFileAlertShow.matches(action)) {
        return action.fileName;
    }

    return state;
}
Example #28
Source File: reducer.ts    From wiregui with MIT License 5 votes vote down vote up
wgConfig: Reducer<WgConfigState> = (state = INITIAL_STATE, action) => {
  return produce(state, (draft) => {
    switch (action.type) {
      case WgConfigTypes.fetchFiles: {
        const { files } = action.payload;
        draft.files = files;
        ipcRenderer.send("WgConfigStateChange", draft.files.map(file => ({
          name: file.name,
          path: file.path,
          active: file.active,
        })));
        break;
      }

      case WgConfigTypes.addFile: {
        const { file } = action.payload;
        draft.files.push(file);
        ipcRenderer.send("WgConfigStateChange", draft.files.map(file => ({
          name: file.name,
          path: file.path,
          active: file.active,
        })));
        break;
      }

      case WgConfigTypes.deleteFile: {
        const { filename } = action.payload;
        draft.files = draft.files.filter((file) => file.name !== filename);
        ipcRenderer.send("WgConfigStateChange", draft.files.map(file => ({
          name: file.name,
          path: file.path,
          active: file.active,
        })));
        break;
      }

      case WgConfigTypes.updateStatus: {
        const { activeTunnelName } = action.payload;

        draft.activeTunnelName = activeTunnelName;
        draft.files = draft.files.map((file) => {
          file.active = file.name === activeTunnelName;

          if (file.active) {
            file.lastConnectAt = new Date().toISOString();
            localStorage.setItem(file.name, file.lastConnectAt);
          }

          return file;
        });
        ipcRenderer.send("WgConfigStateChange", draft.files.map(file => ({
          name: file.name,
          path: file.path,
          active: file.active,
        })));
        break;
      }

      default: {
        break;
      }
    }
  });
}
Example #29
Source File: reducers.ts    From pybricks-code with MIT License 5 votes vote down vote up
updateAvailable: Reducer<boolean> = (state = false, action) => {
    if (serviceWorkerDidUpdate.matches(action)) {
        return true;
    }

    return state;
}