0

I have a component, which is A and on success of some form filling, i route the user to the B component. Now when the user clicks on back button of browser, instead of going back to A component, i re route him to the Home Page

App.js

<Route exact path="/">
   <Root />
 </Route>
 <Route path="/home">
   <Home />
 </Route>
 <Route path="/a">
   <A />
 </Route>
 <Route path="/b">
   <B />
 </Route>

A.js

 componentDidMount() {
    console.log("api call");
  }

  handleSubmit = () => {
    // api success
    this.props.history.push({
      pathname: "/b",
      search: "?viewType=success"
    });
  };

B.js

backListener() {
    if (this.props.history.action === "POP") {
      let viewType = new URLSearchParams(this.props.location?.search)?.get(
        "viewType"
      );
      if (viewType === "success") {
        return this.props.history.replace("/home");
      }
      return this.props.history.replace("/");
    }
  }

  componentDidMount() {
    window.addEventListener("popstate", this.backListener);
  }

  componentWillUnmount() {
    this.backListener();
    window.removeEventListener("popstate", this.backListener);
  }

Even though i am pushing the route to /home, but i can see the A.js log of api calling

I don't want to render the A.js from B when the browser back button is clicked.

What am i doing wrong here

Sandbox

Steps:

  1. Click on Go To A
  2. Click on Submit
  3. Click on back button of sandbox
  4. In the console its showing api call (2 times)

How could i override the back button component load when i am pushing the state on componentWillUnmount ?

dev
  • 665
  • 5
  • 19
  • maybe [this](https://stackoverflow.com/questions/39342195/intercept-handle-browsers-back-button-in-react-router) issue can help? – Andrey Nov 05 '21 at 09:04

0 Answers0