How to use typescript-fsa-reducers - 10 common examples

To help you get started, we’ve selected a few typescript-fsa-reducers examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github raviqqe / tasks / src / state / settings.ts View on Github external
export const actionCreators = {
  setAlarmVolume,
  setNotificationState
};

export type IActionCreators = typeof actionCreators;

export const initialState = {
  alarmVolume: 0.5, // 0 to 1
  notificationOn: notification.permission()
};

export type IState = typeof initialState;

export const reducer = reducerWithInitialState(initialState)
  .case(setAlarmVolume, (state, alarmVolume) => ({ ...state, alarmVolume }))
  .case(setNotificationState, (state, notificationOn) => ({
    ...state,
    notificationOn
  }));

export async function initializeStore(store: Store): Promise {
  const setPermission = (permission: boolean | null) =>
    store.dispatch(setNotificationState(permission));

  if (notification.permission() === null) {
    setPermission(await notification.requestPermission());
  }

  setPermission(notification.permission());
  notification.onPermissionChange(setPermission);
github Azure / azure-iot-explorer / src / app / login / reducer.ts View on Github external
/***********************************************************
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License
 **********************************************************/
import { reducerWithInitialState } from 'typescript-fsa-reducers';
import { ConnectionStateType, connectionStateInitial } from './state';
import { setConnectionStringAction, SetConnectionStringActionParameter } from './actions';
import { CONNECTION_STRING_NAME_LIST, CONNECTION_STRING_LIST_MAX_LENGTH } from '../constants/browserStorage';

const reducer = reducerWithInitialState(connectionStateInitial())
    .case(setConnectionStringAction, (state: ConnectionStateType, payload: SetConnectionStringActionParameter) => {
        // save connection string to local storage with a max length of ${CONNECTION_STRING_LIST_MAX_LENGTH}
        if (payload && payload.connectionStringList) {
            const recentItems = payload.connectionStringList.slice(0, CONNECTION_STRING_LIST_MAX_LENGTH);
            localStorage.setItem(CONNECTION_STRING_NAME_LIST, recentItems.join(','));
        }
        else {
            localStorage.setItem(CONNECTION_STRING_NAME_LIST, payload.connectionString);
        }

        return state.merge({
            connectionString: payload.connectionString,
        });
    });
export default reducer;
github Azure / azure-iot-explorer / src / app / devices / deviceList / reducer.ts View on Github external
* Licensed under the MIT License
 **********************************************************/
import { Map as ImmutableMap, fromJS } from 'immutable';
import { reducerWithInitialState } from 'typescript-fsa-reducers';
import { deviceListStateInitial, DeviceListStateType } from './state';
import { listDevicesAction, clearDevicesAction, deleteDevicesAction, addDeviceAction } from './actions';
import { DeviceSummary } from './../../api/models/deviceSummary';
import { SynchronizationStatus } from '../../api/models/synchronizationStatus';
import { DeviceIdentity } from '../../api/models/deviceIdentity';
import DeviceQuery from '../../api/models/deviceQuery';
import { BulkRegistryOperationResult } from '../../api/models/bulkRegistryOperationResult';
import { DataPlaneResponse, Device } from '../../api/models/device';
import { transformDevice } from '../../api/dataTransforms/deviceSummaryTransform';
import { HEADERS } from '../../constants/apiConstants';

const reducer = reducerWithInitialState(deviceListStateInitial())
    .case(listDevicesAction.started, (state: DeviceListStateType, payload: DeviceQuery) => {
        return state.merge({
            deviceQuery: {...payload},
            devices: state.devices.merge({
                deviceListSynchronizationStatus: SynchronizationStatus.working
            })
        });
    })
    // tslint:disable-next-line: cyclomatic-complexity
    .case(listDevicesAction.done, (state: DeviceListStateType, payload: {params: DeviceQuery} & {result: DataPlaneResponse}) => {
        const deviceList = new Map();
        const devices = payload.result.body || [];
        devices.forEach(item => deviceList.set(item.DeviceId, transformDevice(item)));
        const continuationTokens = (state.deviceQuery.continuationTokens && [...state.deviceQuery.continuationTokens]) || [];
        const currentPageIndex = payload && payload.params && payload.params.currentPageIndex;
github xdave / typescript-fsa-redux-thunk / src / issue-22.spec.ts View on Github external
const initialState = {
	someTest: {
		value: '',
	},
};
type State = typeof initialState;

const create = actionCreatorFactory('test');
const createAsync = asyncFactory(create);

const setStuff = createAsync(
	'set stuff',
	async (params, dispatch, getState, extraArgument) => extraArgument,
);

const reducer = reducerWithInitialState(initialState)
	.case(setStuff.async.done, (state, { result }) => ({
		...state,
		someTest: {
			value: result.fake,
		},
	}))
	.build();

describe(`issue #22`, () => {
	it(`should be able to pass the extraArgument from middleware`, async () => {
		/**
		 * You need to cast the type here, as the overload for withExtraArgument
		 * is completely useless.
		 */
		const middleware: ThunkMiddleware<
			State,
github xdave / typescript-fsa-redux-thunk / src / issue-17.spec.ts View on Github external
it(`should be able to run normally (returning PromiseLike)`, () => {
		const create = actionCreatorFactory();
		const createAsync = asyncFactory(create);

		const example = createAsync(
			'example',
			async (bar: string, dispatch, getState) => {
				return `${getState().foo} ${bar}`;
			},
		);

		reducerWithInitialState({ foo: 'foo' }).case(
			example.async.done,
			(state, { params, result }) => ({ foo: result }),
		);
	});
github raviqqe / tasks / src / state / environment.ts View on Github external
const actionCreator = actionCreatorFactory("ENVIRONMENT");

const setWindowSmall = actionCreator("SET_WINDOW_SMALL");
const setPointerAvailable = actionCreator("SET_POINTER_AVAILABLE");
const setTouchable = actionCreator("SET_TOUCHABLE");

export const initialState = {
  pointerAvailable,
  touchable,
  windowSmall
};

export type IState = typeof initialState;

export const reducer = reducerWithInitialState(initialState)
  .case(setWindowSmall, (state, windowSmall) => ({
    ...state,
    windowSmall
  }))
  .case(setPointerAvailable, (state, pointerAvailable) => ({
    ...state,
    pointerAvailable
  }))
  .case(setTouchable, (state, touchable) => ({ ...state, touchable }));

export function initializeStore(store: Store): void {
  onWindowSizeChange(windowSmall =>
    store.dispatch(setWindowSmall(windowSmall))
  );
  onTouchabilityChange((touchable: boolean) =>
    store.dispatch(setTouchable(touchable))
github raviqqe / tasks / src / state / timer.ts View on Github external
const actionCreator = actionCreatorFactory("TIMER");

export const actionCreators = {
  playAlarm: (): ThunkAction => (_, getState) =>
    audio.playAlarm(getState().settings.alarmVolume),
  toggleTimer: actionCreator("TOGGLE_TIMER")
};

export type IActionCreators = typeof actionCreators;

export const initialState = { on: false };

export type IState = typeof initialState;

export const reducer = reducerWithInitialState(initialState).case(
  actionCreators.toggleTimer,
  state => ({ on: !state.on })
);

export const persistent = false;
github globis-org / react-enterprise-boilerplate / src / reducers / github.ts View on Github external
import * as actions from 'actions/github';
import { Member, User } from 'services/github';

export interface GithubState {
  members: Member[];
  users: User[];
  usersSearchStatus: null | 'searching' | 'failed';
}

const initialState: GithubState = {
  members: [],
  users: [],
  usersSearchStatus: null,
 };

export const githubReducer = reducerWithInitialState(initialState)
  .case(
    actions.setMembers,
    (state, { members }) => ({ ...state, members }),
  )
  .case(
    actions.searchUsers.started,
    (state) => ({ ...state, usersSearchStatus: 'searching' }),
  )
  .case(
    actions.searchUsers.failed,
    (state) => ({ ...state, usersSearchStatus: 'failed' }),
  )
  .case(
    actions.searchUsers.done,
    (state, payload) => ({
      ...state,

typescript-fsa-reducers

Fluent syntax for defining typesafe Redux reducers on top of typescript-fsa.

MIT
Latest version published 4 years ago

Package Health Score

50 / 100
Full package analysis

Popular typescript-fsa-reducers functions