D
D
dim5on2018-11-29 13:38:38
JavaScript
dim5on, 2018-11-29 13:38:38

How to update multiple state values ​​using one function?

Good afternoon ! I have a state like this:

state = {
    photos : {
      driverPhoto : null,
      passportPhoto : null,
      driverLicensePhoto: null,
    },
  };

There is a function that calls camera roll and sets the selected image to the state.
useLibraryHandler = async () => {
    await this.askPermissionsAsync();
    let result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      aspect: [4, 3]
    });
    this.setState({ photos : { ...this.state.photos, driverPhoto : result.uri } });
  };

Here is the element that calls the function:
<TouchableHighlight onPress={this.useLibraryHandler}></TouchableHighlight>

Can you please tell me how to rewrite the function so that it can be called for example like this?
So that the function can be used in different places and update different state elements.
<TouchableHighlight onPress={this.useLibraryHandler('driverPhoto')}></TouchableHighlight>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexKeller, 2018-11-29
@dim5on

So pass the name of a specific element as a separate prop:

<TouchableHighlight onPress={this.useLibraryHandler} photoType="driverPhoto" />
No closures will be needed, just read the passed string.
let newPhotos = {...this.state.photos};
newPhotos[this.props.photoType] = result.uri;
this.setState({ photos : newPhotos });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question