Trying to change the value of one object within an array when I perform an image upload.
Image is coming from a child component with an identifying name, then I loop through the array (stored in state) and try to replace the corresponding object's image prop. Also attempted with a forEach.
I've tried all of the solutions on this answer and this answer, but sadly getting no where.
Here are my two latest attempts:
handleImageUpload = (data) => {
// method 1
for (let i = 0; i <= this.state.artists.length; i++) {
console.log(data);
if (this.state.artists[i].artist === data.artist) {
let artists = [...this.state.artists];
let newArtistEdit = {
name: data.name,
image: data.image,
};
artists[i] = newArtistEdit;
this.setState({ artists });
} else return;
}
// method 2, using immutability helper
for (let i = 0; i <= this.state.artists.length; i += 1) {
try {
if (this.state.artists[i].artist === data.artist) {
this.setState((prevState) => ({
artists: update(this.state.artists, {
i: { image: { $set: data.image } },
}),
}));
}
} catch (error) {
console.log(error.message);
}
}
};
Any ideas why the image prop for artist[i] is never getting updated?
For reference: method 1 doesn't update anything, and method 2 adds a new state property called 'null', containing the image.