Created
February 20, 2020 07:50
-
-
Save mansarip/0321d39d5d6cade0e7b79bc1febd63b7 to your computer and use it in GitHub Desktop.
Clone array then update
This file contains hidden or 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
// katakan ini original state | |
this.state = { | |
products: [ | |
{ | |
id: 1234, | |
name: "chicken", | |
amount: 100 | |
}, | |
{ | |
id: 1235, | |
name: "beef", | |
amount: 200 | |
} | |
] | |
}; | |
// data dari API punya response | |
let newData = { | |
id: 1235, | |
name: "beef", | |
amount: 300 | |
}; | |
// cara2 ni kita guna 'cloning' punya style. | |
// maksudnya copy sebijik dari array original, | |
// kemudian baru manipulate dari hasil yang kita copy tu. | |
// dan akhirnya baru update state dengan array yg baru tu. | |
// * lupa pasal "prevState" sebab asyik guna hook je | |
// cara 1: cari terus object dalam array | |
// ======================================================== // | |
// 1) clone array | |
let newArray = [...this.state.products]; // (... = "spread operator") | |
// 2) find id yang terlibat dari array tadi | |
// "theProduct" akan refer ke object beef sepatutnya. | |
let theProduct = newArray.find(product => product.id === newData.id); // cari id yang sepadan dalam array | |
// 3) update product. | |
// amik amount dari data yang baru. | |
// note: "theProduct" merujuk kepada item dalam newArray. jadi sebenarnya kita update item dalam "newArray" | |
theProduct.amount = newData.amount; | |
// 4) update state | |
this.setState({ | |
products: newArray | |
}); | |
// 5) habis. | |
// cara 2: replace whole element (object dalam array, bukan array tu) | |
// ======================================================== // | |
// 1) clone array | |
let newArray = [...this.state.products]; // (... = "spread operator") | |
// 2) find index by id yang terlibat dari array tadi | |
// "theProduct" akan refer ke object beef sepatutnya. | |
let theProductIndex = newArray.findIndex(product => product.id === newData.id); // cari id yang sepadan dalam array | |
newArray[theProductIndex] = newData; // terus ganti tempat | |
// 4) update state | |
this.setState({ | |
products: newArray | |
}); | |
// 5) habis. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment