Jothi Kannan
Jothi Kannan

Reputation: 3358

React native push with multiple key and value

I have a group of checkboxes, whenever I select a checkbox I need to push an array of data, like { 'index':1, 'photo':'sample.png' } to state, and whenever I unselecting the checkbox, I need to remove it from the state. after I need to loop through the state to get index and photo to be used

handleSelection = async (media, index, isSelected) => {
    alert(index);
    if (isSelected == true) {
        this.state.mediaSelected.push(media.photo);
    } else {
     this.state.mediaSelected.splice(this.state.mediaSelected.indexOf(media.photo), 1);
    }
     console.warn(this.state.mediaSelected);
  }

this is working for single value without the key, is there any way to push it with key and value?

Upvotes: 0

Views: 2310

Answers (2)

Harish Soni
Harish Soni

Reputation: 1896

Try this: Sorry I am working as well as answering your question so it is taking time.

handleSelection = async (media, index, isSelected) => {
    let selectPhotosObj = this.state.selectPhotosObj || [];
    if (isSelected == true) {
        const data = { index, photo: media.photo };
        //this.state.selectedPhotoObj will be the container for your object.
        selectPhotosObj.push(data)
        //need to set the new Array of Object to the state.
        this.setState({ mediaSelected: media.photo, selectPhotosObj });
    } else {
        const removedPhoto = this.state.mediaSelected.filter(value => value !== media.photo);
        selectPhotosObj = this.state.selectedPhotosObj.filter(value => value.index !== index);
        this.setState({
            mediaSelected: removedPhoto,
            selectPhotosObj

        })
    }
    console.warn(selectPhotosObj);
}

Upvotes: 1

Aureo Beck
Aureo Beck

Reputation: 759

You should always update state with this.setState in your case would be something like this:

handleSelection = async (media, index, isSelected) => {
alert(index);
if (isSelected == true) {
    this.setState({
        mediaSelected: this.state.mediaSelected.push({
            index, 
            photo: media.photo 
    }) 
});
} else {
    this.setState({
        mediaSelected: this.state.mediaSelected.splice(this.state.mediaSelected.indexOf(media.photo), 1)
    });
}
console.warn(this.state.mediaSelected);

}

Upvotes: 1

Related Questions