How to use immer - 10 common examples

To help you get started, we’ve selected a few immer 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 axisgroup / RxQ / src / session.js View on Github external
// https://tools.ietf.org/html/rfc6902#page-3
                  // https://tools.ietf.org/html/rfc6901#section-5
                  const arrayPath = patch.path.split("/").filter(s => s !== "");
                  return {
                    ...patch,
                    path: [key, ...arrayPath]
                  };
                });

                return [...acc, ...transformedPatches];
              }, []);
              return {
                ...reqResp,
                response: {
                  ...reqResp.response,
                  result: applyPatches(acc.response.result, patches)
                }
              };
            },
            {
github nusmodifications / nusmods / www / src / js / views / tetris / board.ts View on Github external
export function rotatePieceLeft(piece: Piece): Piece {
  if (piece.tiles.length === 0) return piece;

  return produce(piece, (draft) => {
    const newTiles = [];
    // When turning leftwards the first row becomes the first column reversed
    for (let row = 0; row < draft.tiles[0].length; row++) {
      newTiles.push(draft.tiles.map((column) => column[row]).reverse());
    }
    draft.tiles = newTiles;

    pushPieceInBounds(draft);
  });
}
github zenika-open-source / immutadot / packages / immutadot-benchmark / src / setDeepProp.js View on Github external
},
        },
      ],
      otherProp: 'aze1',
    },
    other: { prop: 'baz' },
  }

  // Prepare immutable state
  const immutableState = Immutable.fromJS(baseState)

  // Prepare seamless state
  const seamlessState = Seamless.from(baseState)

  // Disable immer auto freeze
  setAutoFreeze(false)

  const benchmark = benchmarkSuite.createBenchmark(
    'Set a deeply nested property',
    (key, result) => {
      if (key === 'immutable') return
      expect(result).toEqual({
        nested1: {
          arr1: [
            {
              nested2: {
                arr2: [
                  {
                    nested3: {
                      arr3: [
                        {
                          nested4: {
github nusmodifications / nusmods / website / src / bootstrapping / configure-store.ts View on Github external
import rootReducer from 'reducers';
import requestsMiddleware from 'middlewares/requests-middleware';
import ravenMiddleware from 'middlewares/raven-middleware';
import { setAutoFreeze } from 'immer';

import { FSA, GetState } from 'types/redux';
import { State } from 'types/state';

// For redux-devtools-extensions - see
// https://github.com/zalmoxisus/redux-devtools-extension
// eslint-disable-next-line no-underscore-dangle
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

// immer uses Object.freeze on returned state objects, which is incompatible with
// redux-persist. See https://github.com/rt2zz/redux-persist/issues/747
setAutoFreeze(false);

export default function configureStore(defaultState?: State) {
  const middlewares = [ravenMiddleware, thunk, requestsMiddleware];

  if (process.env.NODE_ENV === 'development') {
    /* eslint-disable */
    const { createLogger } = require('redux-logger');
    /* eslint-enable */
    const logger = createLogger({
      level: 'info',
      collapsed: true,
      duration: true,
      diff: true,
      // Avoid diffing actions that insert a lot of stuff into the state to prevent console from lagging
      diffPredicate: (getState: GetState, action: FSA) =>
        !action.type.startsWith('FETCH_MODULE_LIST') && !action.type.startsWith('persist/'),
github engineforce / ImmutableAssign / debug / benchmarks.js View on Github external
Seamless = require('../node_modules/seamless-immutable/seamless-immutable.production.min');
    //Seamless = require('seamless-immutable'); // This will also be production, because process.env.NODE_ENV = "production"

    Immutable = require('immutable');

    timm = require('timm');

    var _isDevel = false;

    var deepFreeze = require("deep-freeze-strict");

    var iassign = require("../src/iassign");

    var immer = require("immer");
    immer.setAutoFreeze(false);
    var produce = immer.default;

    var INITIAL_OBJECT = {
        toggle: false,
        b: 3,
        str: 'foo',
        d: {
            d1: 6,
            d2: 'foo',
            toggle: false,
            d9: {
                b: {
                    b: {
                        b: 1
                    }
                }
github node-gh / gh / src / cmd.ts View on Github external
import { createGlobalConfig, getGlobalPackageJson, getUserHomePath } from './configs'
import { prepend, safeReaddir, safeImport, safeRealpath, safeWhich } from './fp'
import * as git from './git'
import { getGitHubInstance } from './github'
import { spawnSync, execSyncInteractiveStream } from './exec'
import { readFileSync, writeFileSync } from 'fs'
import * as userhome from 'userhome'

const testing = process.env.NODE_ENV === 'testing'

// Make Fluture Play nicely with Sanctuary
const S = create({ checkTypes: true, env: env.concat(flutureEnv) })

// Allow mutation of options when not testing
// https://immerjs.github.io/immer/docs/freezing
setAutoFreeze(testing)

Future.debugMode(testing)

interface CommandInterface {
    name: string
    isPlugin?: boolean
    DETAILS: {
        alias: string
        description: string
        commands: string
        options: object
        shorthands: object
    }
    run: (options?: any, done?: any) => {}
}
github Canner / canner / packages / canner / src / hooks / useOnDeploy.js View on Github external
// @flow

import { useCallback } from 'react';
import RefId from 'canner-ref-id';
import produce, { setAutoFreeze } from 'immer';
import {
  set, get, isArray, isPlainObject,
} from 'lodash';

setAutoFreeze(false);

export default function ({
  onDeploy,
  removeOnDeploy,
  refId,
  routes
}: {
  onDeploy: Function,
  removeOnDeploy: Function,
  refId: RefId,
  routes: Array<string>
}) {
  const firstKey = routes[0];
  const _removeOnDeploy = useCallback((arg1: string, callbackId: string) => {
    if (callbackId) {
      return removeOnDeploy(arg1, callbackId);
github zenika-open-source / immutadot / packages / immutadot-benchmark / src / updateTodos.js View on Github external
})
  }

  // Prepare immutable state
  const todoRecord = Immutable.Record({
    todo: '',
    done: false,
    someThingCompletelyIrrelevant: [],
  })
  const immutableState = Immutable.List(baseState.map(todo => todoRecord(todo)))

  // Prepare seamless state
  const seamlessState = Seamless.from(baseState)

  // Disable immer auto freeze
  setAutoFreeze(false)

  const unmodifiedSize = listSize - modifySize
  const randomBounds = () => {
    const start = Math.floor(Math.random() * unmodifiedSize)
    return [start, start + modifySize]
  }

  const benchmark = benchmarkSuite.createBenchmark(
    title,
    (key, result) => {
      if (key === 'immutable') return
      let trues = 0, falses = 0
      result.forEach(todo => todo.done ? trues++ : falses++)
      expect(trues).toBe(modifySize)
      expect(falses).toBe(unmodifiedSize)
      trues = falses = 0
github pietrzakadrian / bank / frontend / app / containers / LanguageProvider / reducer.js View on Github external
/*
 *
 * LanguageProvider reducer
 *
 */
import produce, { setAutoFreeze } from 'immer';

import { DEFAULT_LOCALE } from 'i18n';
import { CHANGE_LOCALE } from './constants';

export const initialState = {
  locale: DEFAULT_LOCALE,
};

setAutoFreeze(false);
/* eslint-disable default-case, no-param-reassign */
const languageProviderReducer = produce((draft, action) => {
  switch (action.type) {
    case CHANGE_LOCALE:
      draft.locale = action.locale;
      break;
  }
}, initialState);

export default languageProviderReducer;
github knpwrs / redux-ts-utils / src / handle-action.ts View on Github external
return (state: S | undefined, action: ReturnType<AC>) => {
    if (action.type === ac.type && state) {
      if (isDraftable(state)) {
        const draft = createDraft(state);
        const reResult = re(draft, action);
        const finishedDraft = finishDraft(draft);

        if (finishedDraft === state && reResult !== undefined) {
          return reResult;
        }

        return finishedDraft;
      }
      // Support primitive-returning reducers
      return re(state as Draft<S>, action);
    }
    return (state || s) as any;
  };
}

immer

Create your next immutable state by mutating the current one

MIT
Latest version published 2 months ago

Package Health Score

93 / 100
Full package analysis

Popular JavaScript code snippets

Find secure code to use in your application or website