0

I am doing file selection and push the data into an array but if the selected data has already exist in the array I want to remove it.

I am pushing my data :

_setSelectedFile(file_uri, file_key){
    let selectedFiles = [...this.state.selectedFiles];
    selectedFiles.push({ file_uri: file_uri, file_key: file_key });
    this.setState({ selectedFiles });
}

The output of my array is something like this :

[
    {
        file_uri: "ph://9F983DBA-EC35-42B8-8773-B597CF782EDD/L0/001", 
        file_key: "2"
    },
    {
        file_uri: "ph://CC95F08C-88C3-4012-9D6D-64A413D254B3/L0/001", 
        file_key: "5"
    }
]

I stored the file_key as a reference when removing it later. I saw this answer Delete item from state array in react but not sure how to apply it since the question from the discussion is referring to one-dimensional array.

Eaten Taik
  • 578
  • 2
  • 5
  • 21

1 Answers1

0

I tried out some trick and apparently it's working in my case. Hope this helps others too.

_setSelectedFile(file_uri, file_key){
    var isExist = false;
    var selectedFileKey = null;

    let selectedFiles = [...this.state.selectedFiles];

    if(this.state.selectedFiles != null){
      this.state.selectedFiles.map((data, i)=>{
        if(data.file_key === file_key){
          isExist = true;
          selectedFileKey = i;
        }
      })
    }

    if(isExist == true){
      selectedFiles.splice(selectedFileKey, 1);
      this.setState({selectedFiles: selectedFiles});
    } else {
      selectedFiles.push({ file_uri: file_uri, file_key: file_key });
      this.setState({ selectedFiles });
    }
  }

So I do mapping and check if the data is already exist then assign isExist = true and store the key value selectedFileKey = i.

With isExist set as true I can proceed with removing the data from my array.

Eaten Taik
  • 578
  • 2
  • 5
  • 21
  • 1
    Instead of mapping through and setting `isExist`, simply filter the `selectedFiles` array using the `file_key`. Set the array returned from filter to `selectedFiles` state. Improves code readability. – Nishant Nair Jun 11 '19 at 18:27