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]);
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</>);
}