1

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

4
  • Can you explain in what way it doesn't work? Commented Jul 9, 2018 at 19:59
  • It actually throws a syntax error with unexpected token , Commented Jul 9, 2018 at 20:01
  • @juicy89 Yes {images[imageIndex]: result.uri} is not a valid object literal. Commented Jul 9, 2018 at 20:04
  • Both your answers worked perfectly as expected. Without sounding ridiculous, is one preferred over the other in a general sense? I only ask as I'm still relatively new to JS Commented Jul 9, 2018 at 20:11

3 Answers 3

5

Use Array.splice method.

this.setState(prevState => {
  const { images } = prevState;
  images.splice(imageIndex, 0, result.uri);
  return images;
})
Sign up to request clarification or add additional context in comments.

Comments

2

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 })
  }

Comments

1

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
  );
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.