1

In React, I have code like this:

<Router basename='/app'>
  <main>
    <Menu active={menu} close={this.closeMenu} />
    <Overlay active={menu} onClick={this.closeMenu} />
    <AppBar handleMenuIcon={this.handleMenuIcon} title='Test' />
    <Route path='/customers/:id' component={Customers} />
    <Route path='/products/:id' component={Products} />
  </main>
</Router>

Every time /customers/:id or /products/:id is accessed, I want to log the access by making an ajax call to a backend service. The fields I will be logging include the referrer URL, the current URL, and a randomly generated session ID (random base 64 integer) What's the best way to do that when I am using the Router component from react-router version 1.0.0.

  • Because React code executes on the client, a better approach would be to log requests on the server-side. – Richard Feb 27 '19 at 18:00
  • @Richard Isn't that what they asked for? " I want to log the access by making an ajax call to a backend service" – Dave Newton Feb 27 '19 at 18:08
  • The user wants to 'log the access by making an ajax call.' A better approach would be to log the request when it happens on the express/koa/rails/whatever server is serving the API data. – Richard Feb 27 '19 at 18:10
  • 1
    @Richard Oh, you're saying that on the API side to log it there rather than make a *separate* Ajax call? That's fine if the data is coming from the server (which it may not be) or that they have the ability to modify the API code (which may not be the case). – Dave Newton Feb 27 '19 at 22:21

1 Answers1

0

This has been answered with this question https://stackoverflow.com/a/44410281/5746996

But in essense:

@withRouter
class App extends React.Component {

  static propTypes = {
    location: React.PropTypes.object.isRequired
  }

  // ...

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      this.onRouteChanged();
    }
  }

  onRouteChanged() {
    console.log("ROUTE CHANGED");
  }

  // ...
  render(){
    return <Switch>
        <Route path="/" exact component={HomePage} />
        <Route path="/checkout" component={CheckoutPage} />
        <Route path="/success" component={SuccessPage} />
        // ...
        <Route component={NotFound} />
      </Switch>
  }
}

Use the location property in the props property when you have added the react-router. Test to see if it has changed with each update - if it has, you can send it.

Tobin
  • 1,158
  • 11
  • 21