Last active
October 25, 2023 03:43
-
-
Save epoch/8a800239e01ce68daf2266d25818d41f to your computer and use it in GitHub Desktop.
react immutable update patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// shorter console.log | |
const log = (...args) => console.log(...args) | |
// arrays | |
const ingredients = ['bread', 'cheese', 'tomato'] | |
// shallow clone using slice | |
log(ingredients.slice(0)) | |
// shallow clone using Array.from | |
log(Array.from(ingredients)) | |
// shallow clone using array spread | |
log([...ingredients]) | |
// immutable delete using filter | |
log( | |
ingredients.filter(layer => layer === 'cheese') | |
) | |
// immutable add using array spread | |
log( | |
[...ingredients, 'pineapple'] | |
) | |
// immutable update using map & if statement | |
log( | |
ingredients.map(layer => { | |
if (layer === 'cheese') { | |
return 'cheeessssyyy' | |
} else { | |
return layer | |
} | |
}) | |
) | |
// immutable update using map & ternary | |
log( | |
ingredients.map(layer => | |
layer === 'cheese' | |
? 'cheeessssyyy' | |
: layer | |
) | |
) | |
// object | |
const user = { | |
name: 'dt', | |
color: 'mistyrose', | |
age: 400 | |
} | |
// shallow clone using Object.assign | |
log( | |
Object.assign({}, user) | |
) | |
// shallow clone using spread | |
log( | |
{ ...user } | |
) | |
// shallow clone & update | |
log( | |
{ ...user, age: 401 } | |
) | |
// array of objects | |
const horses = [ | |
{ | |
id: 1, | |
name: 'pony', | |
active: true, | |
yearOfBirth: 2007, | |
}, | |
{ | |
id: 2, | |
name: 'arrrrr', | |
active: true, | |
yearOfBirth: 2004, | |
}, | |
{ | |
id: 3, | |
name: 'hoof hearted', | |
active: false, | |
yearOfBirth: 1981, | |
} | |
] | |
// shallow clone array of objects using slice, Array.from & spread | |
// log(horses.slice(0)) | |
// log(Array.from(horses)) | |
// log([...horses]) | |
// update horse with id 1 using map & Object.assign | |
log( | |
horses.map(horse => { | |
if (horse.id === 1) { | |
return Object.assign({} , horse, { active: false }) | |
} else { | |
return horse | |
} | |
}) | |
) | |
// update horse with id 1 using map & object spread | |
log( | |
horses.map(horse => { | |
if (horse.id === 1) { | |
return { ...horse, active: false } | |
} else { | |
return horse | |
} | |
}) | |
) | |
// update horse id 1 using map, object spread & tenary | |
log( | |
horses.map(horse => | |
horse.id === 1 | |
? { ...horse, active: true, nickname: 'horsey' } | |
: horse | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment