So I'm new to React. I'm trying to use the function map to give an id to an array of objects in the state of a Component. But when I iterate over the objects in the function, the resulting array's elements are all equal to each other, which are equal to the last one iterated. I'm using the uuid module to add the unique ids. This is what I have inside the Component, with a better explanation inside comments:
constructor() {
super()
this.state = {
classes: Array(5).fill({
id: null,
name: null
}),
}
}
componentWillMount() {
// This console.log, strangely, logs the state of the Component as if
// this componentWillMount function had already been executed, showing the
// classes with their ids (still the wrong ones). Would appreciate it if
// someone explained that
console.log(this.state.classes)
let classThings = this.state.classes.map(classObject => {
let obj = classObject
obj.id = uuid.v4()
// This logs the object correctly. The console shows, thanks to this,
// five different objects with five different ids
console.log(obj)
return obj
})
this.setState({
classes: classThings
})
// But, for some reason, this one logs the array and all the elements
// inside are equal to te last one logged by the previous console.log
// that is inside the map function, when it should log an array with the
// five different elements
console.log(classThings)
}
Any help would be greatly appreciated. Thanks.
Array#fillis setting all of the elements in the array to the same object, so the most recent change will be what the object contains.