0
# React Addons Update
1
2
React Addons Update is a legacy React addon that provides immutable update operations for JavaScript objects and arrays. It enables efficient state management without mutating original data structures or performing expensive deep copies.
3
4
## Package Information
5
6
- **Package Name**: react-addons-update
7
- **Package Type**: npm
8
- **Language**: JavaScript (ES5)
9
- **Installation**: `npm install react-addons-update`
10
11
## Core Imports
12
13
```javascript
14
import update from 'react-addons-update';
15
```
16
17
For CommonJS:
18
19
```javascript
20
const update = require('react-addons-update');
21
```
22
23
For browser usage with React already loaded:
24
25
```html
26
<!-- development version -->
27
<script src="https://unpkg.com/react-addons-update/react-addons-update.js"></script>
28
<!-- Then use React.addons.update -->
29
```
30
31
## Basic Usage
32
33
```javascript
34
import update from 'react-addons-update';
35
36
// Simple array update
37
const initialArray = [1, 2, 3];
38
const newArray = update(initialArray, {$push: [4]});
39
// Result: [1, 2, 3, 4], initialArray unchanged
40
41
// Object property update
42
const obj = {a: 5, b: 3};
43
const newObj = update(obj, {b: {$set: 6}});
44
// Result: {a: 5, b: 6}, obj unchanged
45
46
// Nested object update
47
const state = {
48
user: {name: 'Alice', preferences: {theme: 'dark'}},
49
posts: [1, 2, 3]
50
};
51
const newState = update(state, {
52
user: {preferences: {theme: {$set: 'light'}}},
53
posts: {$push: [4]}
54
});
55
```
56
57
## Architecture
58
59
React Addons Update uses a command-based approach to immutable updates:
60
61
- **Shallow Copying**: Creates shallow copies of objects/arrays using `shallowCopy()` function
62
- **Command Processing**: Six specialized commands (`$push`, `$unshift`, `$splice`, `$set`, `$merge`, `$apply`) handle different update patterns
63
- **Recursive Updates**: Nested object/array updates are processed recursively
64
- **Immutability**: Original data structures are never modified; always returns new references
65
- **Performance**: Avoids expensive deep copying by only copying at the level where changes occur
66
67
The library ensures data integrity through extensive invariant checking and type validation.
68
69
## Capabilities
70
71
### Update Function
72
73
The main function that returns an updated shallow copy of an object or array without mutating the original.
74
75
```javascript { .api }
76
/**
77
* Returns an updated shallow copy of an object without mutating the original
78
* @param {any} value - The target object/array to update
79
* @param {object} spec - Update specification containing commands
80
* @returns {any} Updated shallow copy of the input value
81
* @throws {Error} Invariant errors for invalid specifications
82
*/
83
function update(value, spec);
84
```
85
86
The `spec` parameter is an object that describes how to update the `value`. It uses special command keys prefixed with `$` to specify different types of updates.
87
88
**Usage Examples:**
89
90
```javascript
91
// Basic object update
92
const person = {name: 'John', age: 30};
93
const updatedPerson = update(person, {age: {$set: 31}});
94
95
// Array manipulation
96
const numbers = [1, 2, 3];
97
const moreNumbers = update(numbers, {$push: [4, 5]});
98
99
// Complex nested update
100
const data = {
101
users: [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}],
102
settings: {theme: 'dark', notifications: true}
103
};
104
const updatedData = update(data, {
105
users: {0: {name: {$set: 'Alice Smith'}}},
106
settings: {$merge: {language: 'en'}}
107
});
108
```
109
110
### Push Command
111
112
Adds items to the end of an array target.
113
114
```javascript { .api }
115
// Command syntax: {$push: array}
116
// Pushes all items in the array to the target array
117
```
118
119
**Usage Example:**
120
121
```javascript
122
const fruits = ['apple', 'banana'];
123
const moreFruits = update(fruits, {$push: ['orange', 'grape']});
124
// Result: ['apple', 'banana', 'orange', 'grape']
125
```
126
127
### Unshift Command
128
129
Adds items to the beginning of an array target.
130
131
```javascript { .api }
132
// Command syntax: {$unshift: array}
133
// Unshifts all items in the array to the target array
134
```
135
136
**Usage Example:**
137
138
```javascript
139
const numbers = [3, 4, 5];
140
const moreNumbers = update(numbers, {$unshift: [1, 2]});
141
// Result: [1, 2, 3, 4, 5]
142
```
143
144
### Splice Command
145
146
Performs splice operations on an array target using standard Array.splice syntax.
147
148
```javascript { .api }
149
// Command syntax: {$splice: array_of_arrays}
150
// Each inner array contains splice arguments: [start, deleteCount, ...items]
151
```
152
153
**Usage Example:**
154
155
```javascript
156
const letters = ['a', 'b', 'c', 'd'];
157
const modified = update(letters, {
158
$splice: [[1, 2, 'x', 'y']] // Remove 2 items at index 1, insert 'x', 'y'
159
});
160
// Result: ['a', 'x', 'y', 'd']
161
162
// Multiple splice operations
163
const data = [1, 2, 3, 4, 5];
164
const result = update(data, {
165
$splice: [
166
[0, 1], // Remove first item
167
[2, 0, 'inserted'] // Insert at index 2
168
]
169
});
170
```
171
172
### Set Command
173
174
Replaces the target entirely with the provided value.
175
176
```javascript { .api }
177
// Command syntax: {$set: any}
178
// Replaces the target entirely with the provided value
179
```
180
181
**Usage Example:**
182
183
```javascript
184
const config = {api: 'v1', timeout: 5000};
185
const newConfig = update(config, {api: {$set: 'v2'}});
186
// Result: {api: 'v2', timeout: 5000}
187
188
// Can set any type
189
const data = {items: [1, 2, 3]};
190
const cleared = update(data, {items: {$set: []}});
191
// Result: {items: []}
192
```
193
194
### Merge Command
195
196
Performs a shallow merge of the provided object with the target object.
197
198
```javascript { .api }
199
// Command syntax: {$merge: object}
200
// Merges the keys of the object with the target (shallow merge)
201
```
202
203
**Usage Example:**
204
205
```javascript
206
const user = {name: 'Alice', age: 25};
207
const updated = update(user, {$merge: {age: 26, city: 'Boston'}});
208
// Result: {name: 'Alice', age: 26, city: 'Boston'}
209
210
// Merge with nested objects
211
const settings = {ui: {theme: 'dark'}, api: {version: 1}};
212
const newSettings = update(settings, {
213
ui: {$merge: {language: 'en'}},
214
api: {$merge: {timeout: 3000}}
215
});
216
```
217
218
### Apply Command
219
220
Applies a function to the current value and updates with the returned result.
221
222
```javascript { .api }
223
// Command syntax: {$apply: function}
224
// Passes current value to function and updates with returned value
225
```
226
227
**Usage Example:**
228
229
```javascript
230
const counter = {count: 5};
231
const incremented = update(counter, {
232
count: {$apply: (x) => x + 1}
233
});
234
// Result: {count: 6}
235
236
// Transform array items
237
const items = {data: [1, 2, 3]};
238
const doubled = update(items, {
239
data: {$apply: (arr) => arr.map(x => x * 2)}
240
});
241
// Result: {data: [2, 4, 6]}
242
243
// Complex transformations
244
const text = {content: ' hello world '};
245
const cleaned = update(text, {
246
content: {$apply: (str) => str.trim().toUpperCase()}
247
});
248
// Result: {content: 'HELLO WORLD'}
249
```
250
251
## Command Rules and Constraints
252
253
### Set Command Exclusivity
254
255
When using `$set`, it must be the only key in the specification object:
256
257
```javascript
258
// Valid
259
update(obj, {field: {$set: 'new value'}});
260
261
// Invalid - will throw error
262
update(obj, {field: {$set: 'new value', $merge: {other: 'data'}}});
263
```
264
265
### Array Command Requirements
266
267
Array commands (`$push`, `$unshift`, `$splice`) require array targets:
268
269
```javascript
270
// Valid
271
update([1, 2, 3], {$push: [4]});
272
273
// Invalid - will throw error
274
update({a: 1}, {$push: [2]});
275
```
276
277
### Type Validation
278
279
All commands validate their inputs and targets:
280
281
```javascript
282
// $apply requires a function
283
update(obj, {field: {$apply: 'not a function'}}); // Throws error
284
285
// $merge requires an object
286
update(obj, {$merge: 'not an object'}); // Throws error
287
288
// Array commands require array values
289
update(arr, {$push: 'not an array'}); // Throws error
290
```
291
292
## Error Handling
293
294
The update function throws invariant errors for:
295
296
- Invalid specification objects (non-objects)
297
- Multiple keys when using `$set` command
298
- Wrong types for command values (e.g., non-function for `$apply`)
299
- Wrong target types for array commands
300
- Invalid splice operation parameters
301
302
Example error handling:
303
304
```javascript
305
try {
306
const result = update(data, {$invalidCommand: 'value'});
307
} catch (error) {
308
console.error('Update specification invalid:', error.message);
309
}
310
```
311
312
## Migration Notes
313
314
This package is deprecated and no longer maintained. For new projects, use [`immutability-helper`](https://github.com/kolodny/immutability-helper) which provides the same API as a drop-in replacement.
315
316
```javascript
317
// Migration
318
// Old: import update from 'react-addons-update';
319
// New: import update from 'immutability-helper';
320
```