Search code examples
javascriptreactjsreact-hooksparent-childuse-state

removing child component from parent component within map loop


In my parent component, I have this code that generates child components based on a usestate hook files:

files.map((fl) => <AudioFileListItem key={fl.id} id={fl.id} customer_id={customer_id} name={fl.name} s3_url={fl.s3_url} />)

Within that child component, I want to have the ability to delete itself from the files hook of its parent or just delete itself from being rendered.

This is my delete function in the child component:

  const handleAudioDelete = (sound_id) => {
    
    var data = {
      "id": sound_id
    };

    if (window.confirm("Are you sure you want to delete this file?")) {
      axios.post(`/delete-file`, data).then(function(result) {
        //remove item from react list through hook
        console.log(result.data);
      });;
    }

  }

Any idea what I can do?

Update!

Added this to parent component and passed it down to child in prop. It successfully updates the value of files in the parent component but it does not remove the child component from the view. I believe this is because all of the child components are already rendered and the map display is not dynamically showing the values of files.

  const handleAudioDelete = (sound_id) => {

var data = {
  "id": sound_id
};

if (window.confirm("Are you sure you want to delete this file?")) {
  var index = files.findIndex(function(o){
    return o.id === sound_id;
  })
  if (index !== -1) files.splice(index, 1);

  setFiles(files);
  console.log(files)
}

  /*
  axios.post(`http://localhost:2000/files/delete-file`, data).then(function(result) {
    //remove item from react list through hook
    console.log(result.data);
  });
  */

}


Solution

  • Assuming files is state, use the element id to filter the state, return all file elements with non-matching id property.

    const handleAudioDelete = (id) => {
      const data = {
        id
      };
    
      if (window.confirm("Are you sure you want to delete this file?")) {
        axios.post(`/delete-file`, data)
          .then(function(result) {
            setFiles(files => files.filter(fl => fl.id !== id));
          });
      }
    }