0

I'm attempting to freeze the keys inside my object so that I don't accidentally update them, as I'm using React Native (0.34.0) and Redux, so I need to use pure functions.

However using the deepFreeze npm package, as well as trying Object.freeze(...) it still let's me mutate my keys on the following code, any help would be appreciated!

var Immutable = require('immutable');
var deepFreeze = require('deep-freeze');

import * as types from '../actions/actionTypes';

const initialState = {
    customBackgroundColour: '#f7f7f7'
};

export default function backgroundColour(state = initialState, action = {}) {

switch (action.type) {
    case types.SET_BACKGROUND_COLOUR:

        deepFreeze(state);
        deepFreeze(action);

        console.log(Object.isFrozen(state)); // true
        console.log(state.customBackgroundColour); // #f7f7f7

        state.customBackgroundColour = 'red';
        console.log(state.customBackgroundColour); // red

        return {
            ...state,
            customBackgroundColour: action.payload.colour
        };
    default:
        return state;
    }
}
Jonathan Lockley
  • 1,320
  • 5
  • 18
  • 28
  • Object.freeze is working fine for me (tested on iOS). What platform are you testing this on? Further, try adding `'use strict'` on top of the file to see if mutating the frozen object will throw an error - it should in strict mode. – jevakallio Jan 19 '17 at 14:02

1 Answers1

1

See https://github.com/facebook/react-native/issues/5316

Strict mode is not enabled by default because facebook has some modules that aren't compliant with strict mode the packager also transpiles files under node_modules, so any library not written with strict mode will break.

I'm using Babel's transform strict plugin to enforce this and it works fine for me. https://babeljs.io/docs/plugins/transform-strict-mode/

Just be aware that it might break if you include non strict modules or Facebook will include non strict modules in the future in ReactNative.

Tieme
  • 62,602
  • 20
  • 102
  • 156