Reputation: 458
I have an app im building in reactjs and react native. I have an array in my state that I'm adding image uri's to.
state = {
images: []
}
The problem lies in that I want to add images uris to this array at a specific index like this
//pass the index I want the image uri assigned to
pickImage = (imageIndex) => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
if (!result.cancelled) {
this.setState({images[imageIndex]: result.uri})
}
}
however, the above doesn't work, can someone point me in the right direction?
Thanks
Upvotes: 1
Views: 6805
Reputation: 93
A new array should be created with a different value in that index. We want to make a new array because it is an antipattern to mutate state. The new array can be created by making a copy of this.state.images and modifying the value at the specific index.
const copyOfImages = [...this.state.images];
copyOfImages[imageIndex] = newValue;
this.setState({images: copyOfImages});
Array.prototype.map can be leveraged to make this code a bit more functional.
this.setState(previousState => ({
images: previousState.images.map(
(image, index) => index === imageIndex ? result.uri : image
);
});
Upvotes: 1
Reputation: 118271
Use Array.splice method.
this.setState(prevState => {
const { images } = prevState;
images.splice(imageIndex, 0, result.uri);
return images;
})
Upvotes: 5
Reputation: 17249
It looks like you're trying to modify state somewhat directly. Try this instead:
pickImage = (imageIndex) => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
const images = { ...this.state };
images[imageIndex] = result.uri;
if (!result.cancelled) {
this.setState({ images })
}
Upvotes: 2