Socket
Socket
Sign inDemoInstall

react-addons-update

Package Overview
Dependencies
Maintainers
9
Versions
62
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-addons-update - npm Package Compare versions

Comparing version 15.5.1 to 15.5.2

35

index.js

@@ -8,40 +8,7 @@ /**

* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule update
*/
/* global hasOwnProperty:true */
'use strict';
var NODE_ENV = process.env.NODE_ENV;
var invariant = function(condition, format, a, b, c, d, e, f) {
if (NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
var invariant = require('fbjs/lib/invariant');
var hasOwnProperty = {}.hasOwnProperty;

@@ -48,0 +15,0 @@

4

package.json
{
"name": "react-addons-update",
"version": "15.5.1",
"version": "15.5.2",
"main": "index.js",

@@ -29,2 +29,2 @@ "repository": "facebook/react",

]
}
}

@@ -33,3 +33,2 @@ (function(f) {

})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (process){
/**

@@ -42,38 +41,7 @@ * Copyright 2013-present, Facebook, Inc.

* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule update
*/
/* global hasOwnProperty:true */
'use strict';
var invariant = function(condition, format, a, b, c, d, e, f) {
if (true) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
var invariant = require('fbjs/lib/invariant');
var hasOwnProperty = {}.hasOwnProperty;

@@ -233,186 +201,59 @@

}).call(this,require('_process'))
},{"_process":2}],2:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
},{"fbjs/lib/invariant":2}],2:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
'use strict';
var cachedSetTimeout;
var cachedClearTimeout;
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
var validateFormat = function validateFormat(format) {};
if ("development" !== 'production') {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
};
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
queueIndex = -1;
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
module.exports = invariant;
},{}]},{},[1])(1)
});

@@ -1,1 +0,1 @@

(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}if(typeof g.React==="undefined"){throw Error("React module should be required before update")}else if(typeof g.React.addons==="undefined"){g.React.addons={}}g.React.addons.update=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){(function(process){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if(!condition){var error;if(format===undefined){error=new Error("Minified exception occurred; use the non-minified dev environment "+"for the full error message and additional helpful warnings.")}else{var args=[a,b,c,d,e,f];var argIndex=0;error=new Error(format.replace(/%s/g,function(){return args[argIndex++]}));error.name="Invariant Violation"}error.framesToPop=1;throw error}};var hasOwnProperty={}.hasOwnProperty;function shallowCopy(x){if(Array.isArray(x)){return x.concat()}else if(x&&typeof x==="object"){return Object.assign(new x.constructor,x)}else{return x}}var COMMAND_PUSH="$push";var COMMAND_UNSHIFT="$unshift";var COMMAND_SPLICE="$splice";var COMMAND_SET="$set";var COMMAND_MERGE="$merge";var COMMAND_APPLY="$apply";var ALL_COMMANDS_LIST=[COMMAND_PUSH,COMMAND_UNSHIFT,COMMAND_SPLICE,COMMAND_SET,COMMAND_MERGE,COMMAND_APPLY];var ALL_COMMANDS_SET={};ALL_COMMANDS_LIST.forEach(function(command){ALL_COMMANDS_SET[command]=true});function invariantArrayCase(value,spec,command){invariant(Array.isArray(value),"update(): expected target of %s to be an array; got %s.",command,value);var specValue=spec[command];invariant(Array.isArray(specValue),"update(): expected spec of %s to be an array; got %s. "+"Did you forget to wrap your parameter in an array?",command,specValue)}function update(value,spec){invariant(typeof spec==="object","update(): You provided a key path to update() that did not contain one "+"of %s. Did you forget to include {%s: ...}?",ALL_COMMANDS_LIST.join(", "),COMMAND_SET);if(hasOwnProperty.call(spec,COMMAND_SET)){invariant(Object.keys(spec).length===1,"Cannot have more than one key in an object with %s",COMMAND_SET);return spec[COMMAND_SET]}var nextValue=shallowCopy(value);if(hasOwnProperty.call(spec,COMMAND_MERGE)){var mergeObj=spec[COMMAND_MERGE];invariant(mergeObj&&typeof mergeObj==="object","update(): %s expects a spec of type 'object'; got %s",COMMAND_MERGE,mergeObj);invariant(nextValue&&typeof nextValue==="object","update(): %s expects a target of type 'object'; got %s",COMMAND_MERGE,nextValue);Object.assign(nextValue,spec[COMMAND_MERGE])}if(hasOwnProperty.call(spec,COMMAND_PUSH)){invariantArrayCase(value,spec,COMMAND_PUSH);spec[COMMAND_PUSH].forEach(function(item){nextValue.push(item)})}if(hasOwnProperty.call(spec,COMMAND_UNSHIFT)){invariantArrayCase(value,spec,COMMAND_UNSHIFT);spec[COMMAND_UNSHIFT].forEach(function(item){nextValue.unshift(item)})}if(hasOwnProperty.call(spec,COMMAND_SPLICE)){invariant(Array.isArray(value),"Expected %s target to be an array; got %s",COMMAND_SPLICE,value);invariant(Array.isArray(spec[COMMAND_SPLICE]),"update(): expected spec of %s to be an array of arrays; got %s. "+"Did you forget to wrap your parameters in an array?",COMMAND_SPLICE,spec[COMMAND_SPLICE]);spec[COMMAND_SPLICE].forEach(function(args){invariant(Array.isArray(args),"update(): expected spec of %s to be an array of arrays; got %s. "+"Did you forget to wrap your parameters in an array?",COMMAND_SPLICE,spec[COMMAND_SPLICE]);nextValue.splice.apply(nextValue,args)})}if(hasOwnProperty.call(spec,COMMAND_APPLY)){invariant(typeof spec[COMMAND_APPLY]==="function","update(): expected spec of %s to be a function; got %s.",COMMAND_APPLY,spec[COMMAND_APPLY]);nextValue=spec[COMMAND_APPLY](nextValue)}for(var k in spec){if(!(ALL_COMMANDS_SET.hasOwnProperty(k)&&ALL_COMMANDS_SET[k])){nextValue[k]=update(value[k],spec[k])}}return nextValue}module.exports=update}).call(this,require("_process"))},{_process:2}],2:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run()}}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;runClearTimeout(timeout)}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i]}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}]},{},[1])(1)});
!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;if(g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,void 0===g.React)throw Error("React module should be required before update");void 0===g.React.addons&&(g.React.addons={}),g.React.addons.update=f()}}(function(){return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n||e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){"use strict";function shallowCopy(x){return Array.isArray(x)?x.concat():x&&"object"==typeof x?Object.assign(new x.constructor,x):x}function invariantArrayCase(value,spec,command){invariant(Array.isArray(value),"update(): expected target of %s to be an array; got %s.",command,value);var specValue=spec[command];invariant(Array.isArray(specValue),"update(): expected spec of %s to be an array; got %s. Did you forget to wrap your parameter in an array?",command,specValue)}function update(value,spec){if(invariant("object"==typeof spec,"update(): You provided a key path to update() that did not contain one of %s. Did you forget to include {%s: ...}?",ALL_COMMANDS_LIST.join(", "),COMMAND_SET),hasOwnProperty.call(spec,COMMAND_SET))return invariant(1===Object.keys(spec).length,"Cannot have more than one key in an object with %s",COMMAND_SET),spec[COMMAND_SET];var nextValue=shallowCopy(value);if(hasOwnProperty.call(spec,COMMAND_MERGE)){var mergeObj=spec[COMMAND_MERGE];invariant(mergeObj&&"object"==typeof mergeObj,"update(): %s expects a spec of type 'object'; got %s",COMMAND_MERGE,mergeObj),invariant(nextValue&&"object"==typeof nextValue,"update(): %s expects a target of type 'object'; got %s",COMMAND_MERGE,nextValue),Object.assign(nextValue,spec[COMMAND_MERGE])}hasOwnProperty.call(spec,COMMAND_PUSH)&&(invariantArrayCase(value,spec,COMMAND_PUSH),spec[COMMAND_PUSH].forEach(function(item){nextValue.push(item)})),hasOwnProperty.call(spec,COMMAND_UNSHIFT)&&(invariantArrayCase(value,spec,COMMAND_UNSHIFT),spec[COMMAND_UNSHIFT].forEach(function(item){nextValue.unshift(item)})),hasOwnProperty.call(spec,COMMAND_SPLICE)&&(invariant(Array.isArray(value),"Expected %s target to be an array; got %s",COMMAND_SPLICE,value),invariant(Array.isArray(spec[COMMAND_SPLICE]),"update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?",COMMAND_SPLICE,spec[COMMAND_SPLICE]),spec[COMMAND_SPLICE].forEach(function(args){invariant(Array.isArray(args),"update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?",COMMAND_SPLICE,spec[COMMAND_SPLICE]),nextValue.splice.apply(nextValue,args)})),hasOwnProperty.call(spec,COMMAND_APPLY)&&(invariant("function"==typeof spec[COMMAND_APPLY],"update(): expected spec of %s to be a function; got %s.",COMMAND_APPLY,spec[COMMAND_APPLY]),nextValue=spec[COMMAND_APPLY](nextValue));for(var k in spec)ALL_COMMANDS_SET.hasOwnProperty(k)&&ALL_COMMANDS_SET[k]||(nextValue[k]=update(value[k],spec[k]));return nextValue}var invariant=require(2),hasOwnProperty={}.hasOwnProperty,COMMAND_PUSH="$push",COMMAND_UNSHIFT="$unshift",COMMAND_SPLICE="$splice",COMMAND_SET="$set",COMMAND_MERGE="$merge",COMMAND_APPLY="$apply",ALL_COMMANDS_LIST=[COMMAND_PUSH,COMMAND_UNSHIFT,COMMAND_SPLICE,COMMAND_SET,COMMAND_MERGE,COMMAND_APPLY],ALL_COMMANDS_SET={};ALL_COMMANDS_LIST.forEach(function(command){ALL_COMMANDS_SET[command]=!0}),module.exports=update},{2:2}],2:[function(require,module,exports){"use strict";function invariant(condition,format,a,b,c,d,e,f){if(validateFormat(format),!condition){var error;if(void 0===format)error=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var args=[a,b,c,d,e,f],argIndex=0;error=new Error(format.replace(/%s/g,function(){return args[argIndex++]})),error.name="Invariant Violation"}throw error.framesToPop=1,error}}var validateFormat=function(format){};module.exports=invariant},{}]},{},[1])(1)});
# react-addons-update
This package provides the React updates add-on.
>**Note:**
>This is a legacy React addon, and is no longer maintained.
>
>We don't encourage using it in new code, but it exists for backwards compatibility.
>The recommended migration path is to use [`immutability-helper`](https://github.com/kolodny/immutability-helper). Its version `1.0.0` is a drop-in replacement.
See <https://facebook.github.io/react/docs/update.html> for more information.
**Importing**
```javascript
import update from 'react-addons-update'; // ES6
var update = require('react-addons-update'); // ES5 with npm
```
If you prefer a `<script>` tag, you can get it from `React.addons.update` with:
```html
<!-- development version -->
<script src="https://unpkg.com/react-addons-update/react-addons-update.js"></script>
<!-- production version -->
<script src="https://unpkg.com/react-addons-update/react-addons-update.min.js"></script>
```
In this case, make sure to put the `<script>` tag after React.
## Overview
React lets you use whatever style of data management you want, including mutation. However, if you can use immutable data in performance-critical parts of your application it's easy to implement a fast [`shouldComponentUpdate()`](https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate) method to significantly speed up your app.
Dealing with immutable data in JavaScript is more difficult than in languages designed for it, like [Clojure](http://clojure.org/). However, we've provided a simple immutability helper, `update()`, that makes dealing with this type of data much easier, *without* fundamentally changing how your data is represented. You can also take a look at Facebook's [Immutable-js](https://facebook.github.io/immutable-js/docs/) and the [Optimizing Performance](https://facebook.github.io/react/docs/optimizing-performance.html) section for more detail on Immutable-js.
### The Main Idea
If you mutate data like this:
```js
myData.x.y.z = 7;
// or...
myData.a.b.push(9);
```
You have no way of determining which data has changed since the previous copy has been overwritten. Instead, you need to create a new copy of `myData` and change only the parts of it that need to be changed. Then you can compare the old copy of `myData` with the new one in `shouldComponentUpdate()` using triple-equals:
```js
const newData = deepCopy(myData);
newData.x.y.z = 7;
newData.a.b.push(9);
```
Unfortunately, deep copies are expensive, and sometimes impossible. You can alleviate this by only copying objects that need to be changed and by reusing the objects that haven't changed. Unfortunately, in today's JavaScript this can be cumbersome:
```js
const newData = extend(myData, {
x: extend(myData.x, {
y: extend(myData.x.y, {z: 7}),
}),
a: extend(myData.a, {b: myData.a.b.concat(9)})
});
```
While this is fairly performant (since it only makes a shallow copy of `log n` objects and reuses the rest), it's a big pain to write. Look at all the repetition! This is not only annoying, but also provides a large surface area for bugs.
## `update()`
`update()` provides simple syntactic sugar around this pattern to make writing this code easier. This code becomes:
```js
import update from 'react-addons-update';
const newData = update(myData, {
x: {y: {z: {$set: 7}}},
a: {b: {$push: [9]}}
});
```
While the syntax takes a little getting used to (though it's inspired by [MongoDB's query language](http://docs.mongodb.org/manual/core/crud-introduction/#query)) there's no redundancy, it's statically analyzable and it's not much more typing than the mutative version.
The `$`-prefixed keys are called *commands*. The data structure they are "mutating" is called the *target*.
## Available Commands
* `{$push: array}` `push()` all the items in `array` on the target.
* `{$unshift: array}` `unshift()` all the items in `array` on the target.
* `{$splice: array of arrays}` for each item in `arrays` call `splice()` on the target with the parameters provided by the item.
* `{$set: any}` replace the target entirely.
* `{$merge: object}` merge the keys of `object` with the target.
* `{$apply: function}` passes in the current value to the function and updates it with the new returned value.
## Examples
### Simple push
```js
const initialArray = [1, 2, 3];
const newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]
```
`initialArray` is still `[1, 2, 3]`.
### Nested collections
```js
const collection = [1, 2, {a: [12, 17, 15]}];
const newCollection = update(collection, {2: {a: {$splice: [[1, 1, 13, 14]]}}});
// => [1, 2, {a: [12, 13, 14, 15]}]
```
This accesses `collection`'s index `2`, key `a`, and does a splice of one item starting from index `1` (to remove `17`) while inserting `13` and `14`.
### Updating a value based on its current one
```js
const obj = {a: 5, b: 3};
const newObj = update(obj, {b: {$apply: function(x) {return x * 2;}}});
// => {a: 5, b: 6}
// This is equivalent, but gets verbose for deeply nested collections:
const newObj2 = update(obj, {b: {$set: obj.b * 2}});
```
### (Shallow) Merge
```js
const obj = {a: 5, b: 3};
const newObj = update(obj, {$merge: {b: 6, c: 7}}); // => {a: 5, b: 6, c: 7}
```
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc