How to use the immer.setAutoFreeze function in immer

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 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
}) {
  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 zewa666 / aurelia-store-examples / immer / src / app.ts View on Github external
import { autoinject } from 'aurelia-framework';
import { Store } from 'aurelia-store';
import produce from 'immer';
import { setAutoFreeze } from 'immer';

import { State } from './state';

setAutoFreeze(false);

@autoinject()
export class App {
  public state: State;

  constructor(private store: Store) {
    this.store.state.subscribe((state) => {
      this.state = state;
    });

    this.store.registerAction(increaseCounter.name, increaseCounter);
    this.store.registerAction(decreaseCounter.name, decreaseCounter);
  }

  public increase() {
    this.store.dispatch(increaseCounter);
github michael-klein / forimmer / dist / forimmer.cjs.development.js View on Github external
'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var produce = require('immer');
var produce__default = _interopDefault(produce);
var React = require('react');

produce.setAutoFreeze(true);

{
  produce.setAutoFreeze(false);
}

function createStore(currentState) {
  var listeners = [];

  function setState(state) {
    currentState = state;
    [].concat(listeners).forEach(function (listener) {
      return listener(currentState);
    });
  }

  function updateState(producer) {
    var newState = produce__default(currentState || {}, function (draft) {
      return producer(draft);
    });
github janryWang / qverse / src / utils.js View on Github external
import produce, { setAutoFreeze } from "immer"
import createDotPathMatcher from "dot-match"
import get from "lodash.get"
export const isFn = val => typeof val == "function"
export const isBool = val => typeof val == "boolean"
export const isObj = val => typeof val == "object"
export const isArr = val => Array.isArray(val)
export const isStr = val => typeof val == "string"

setAutoFreeze(false)

class Controller {
    constructor({ path, options, actions, params, cache }) {
        this.path = path
        this.options = options || {}
        this.actions = actions
        this.params = params || {}
        this.cache = cache
        if (isStr(path)) this.matcher = createDotPathMatcher(path, this.cache)
    }

    filter(fn) {
        this.options.include = fn
        return this
    }

immer

Create your next immutable state by mutating the current one

MIT
Latest version published 8 months ago

Package Health Score

84 / 100
Full package analysis