Search code examples
javascriptreactjsroutesprompt

Delete images if the user is leaving the component React


I have form with a drag and drop component where I can upload images, after this I send these pictures with axios to my backend and save it on server side and then re-render it in a preview mode. My problem is, that if a user uploads some pictures and after that he switches to another page without submitting the form the added pictures are staying on my server side for no reason.

So the question: I want to check inside my component if a user is leaving, show a prompt and if he clicks on the OK button I want to delete all the added pictures from my backend before leaving. How can I detect this?

My simplified snippet:

function MyComp(props) {
     const [Images,setImages] = useState([]) // in this array I store the recieved image's URL
     const [isBlocking,setIsBlocking] = useState(true) // used for prompt

 const handleSubmit = (event) => {
        event.preventDefault();
        setIsBlocking(false)
      }


 return(
        <Grid container className={classes.mainGrid} direction="row" spacing={2}>
            <Grid item xs={4} xl={4}> 
            
            <Prompt when={isBlocking} message="There are unsaved datas. Are you sure you want to leave?"/>
            
            <form className={classes.form} onSubmit={handleSubmit}>
            ... somecode
       </Grid>
      </Grid>
    )
}
export default MyComp

Thanks in advance


Solution

  • Inside React Function Component you can call the prompt when the user is trying to leave , i.e when the component is unmounting

    In Class Component of React you can use React componentWillUnmount() and in Function Component You can use useEffect cleanup function

    Code for Function Component

    
    import React, { useEffect } from "react";
    import { Link } from "react-router-dom";
    
    export default function Home(props) {
      useEffect(() => {
        return function cleanup() {
          alert("unmounting");
         //call api and execute your code here
        };
      }, []);
    
      return (
          <div>
            <Link to="/home">
              On Click I will unmount this component and go to /home
            </Link>
          </div>
        </Link>
      );
    }
    
    
    

    Code for Class Component

    
    import React, { Component } from 'react';
    import { Link } from 'react-router-dom';
    export default class Test extends Component {
      componentWillUnmount() {
        alert('unmounting component');
        //call your code here
      }
      render() {
        return (
          <div>
            <Link to='/home'>
              On Click I will unmount this component and go to /home
            </Link>
          </div>
        );
      }
    }
    
    
    

    You can check this codesandbox if you want any ref

    Edit adoring-sun-dwnde