I have the following sample piece of code that I'm using to learn about the spread operator and updating react state. I understand how it is working, but I don't fully understand how the return {...inst, hobbies}
syntax functions to update the nested hobbies array.
My confusion is due to the fact that when I use hobbies.slice(hobbyIndex,1)
instead of hobbies.splice(hobbyIndex,1)
, my hobbies array does not change event though different hobbyIndex values are being passed in.
My expectation is that if I get a hobbyIndex value of 0, then hobbies should become just the values in the array from index 0 to 1, so basically the first element in the array. My console log confirms that. However, when my app runs, the value of hobbies is still the same as what is in the hobbies list of the randomly selected instructor. Why??
this.state = {
instructors: [
{
name: "Jimmy",
hobbies: ['soccer','reading','sports']
},
{
name: "Paul",
hobbies: ['sailing','skiing','diving']
},
{
name: "Sam",
hobbies: ['eating','sleeping','TV']
},
]
};
const randInst = Math.floor(Math.random() * this.state.instructors.length);
const hobbyIndex = Math.floor(Math.random() * this.state.instructors[randInst].hobbies.length);
const instructors = this.state.instructors.map((inst,idx) => {
if (idx === randInst) {
const hobbies = [...inst.hobbies];
//hobbies.splice(hobbyIndex,1); //this works to remove the specified index
hobbies.slice(hobbyIndex,1); //this works in terms of console.log showing the expected value based on the hobbyIndex value
console.log("value of random selected hobby and hobbies to return: ", hobbyIndex, hobbies);
return {...inst,hobbies} //inst object's hobbies array seems to update when splice is used, but not when slice is use...
}
return inst;
});