Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

200
Vistas
How can I detect browser back button in react class component

I am trying to create a function when user hit browser back button it will run function deleteHeldResort that I created.

Here is my code for deleteHeldResort:

deleteHeldResorts(ReservedInventoryID: number | null = null, refreshHeldResorts: boolean = true) {
    return new Promise((resolve, reject) => {
        this.setState({heldResortsShowLoader: true});
        this.reservationService.deleteHeldResorts(ReservedInventoryID)
            .then(() => {
            refreshHeldResorts && this.getHeldResorts();
            resolve();
        })
        .catch((error: any) => {
            this.catchHeldResortsError(error);
            reject(error);
        });
        this.setState({
            heldResortsShowLoader: false
        });
    });
}

Updated code base:

  handleNavigateBack = useCallback(
    (event) => {
             
           // call your function here with whatever argument your code provides
           this.reservationService.deleteHeldResorts(this.props.resId);

      }
    , []);
  
  useEffect(() => {
    document.addEventListener('popstate', this.handleNavigateBack );
    return () => {
      document.removeEventListener('popstate', this.handleNavigateBack)
    }
}, [this.handleNavigateBack]);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Updated answer: class component based

Since you're using class components, I'm adding this update. Inside the class component having deleteHeldResorts function, you can listen to popstate event: Remark how bind keyword helps us keep the right this.


import React from "react";
import { render } from "react-dom";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleNavigateBack = this.handleNavigateBack.bind(this);
  }

  componentDidMount() {
    document.addEventListener("popstate", this.handleNavigateBack);
  }

  componentWillUnmount() {
    document.removeEventListener("popstate", this.handleNavigateBack);
  }

  handleNavigateBack(event) {
    console.log("inside callback", event);
   // change arguments as you want
    this.deleteHeldResorts(null, false);
  }

  deleteHeldResorts(ReservedInventoryID = null, refreshHeldResorts = true) {
    // your function goes down there content
    console.log("inside deleteHeldResorts");
  }

  render() {
    return <h2>popstate browser listener</h2>;
  }
}

render(<App />, document.getElementById("root"));


Initial answer: function component based

Inside the component having deleteHeldResorts function, you can listen to popstate event:


// your-component.js

function YourComponent() {

   function deleteHeldResorts(ReservedInventoryID: number | null = null, 
                              refreshHeldResorts: boolean = true) {
               // your function content
      }
 
  const handleNavigateBack = useCallback(
    (event) => {
             
           // call your function here with whatever argument your code provides
           deleteHeldResorts(reservedInventoryID,refreshHeldResorts);

      }
  //  depending on your logic, add deps to this array dependency 
    }, [])


  useEffect(() => {
    document.addEventListener('popstate', handleNavigateBack );
    return () => {
      document.removeEventListener('popstate', handleNavigateBack)
    }
  }, [handleNavigateBack])

 return ( <>something dope</>);
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda