Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an interceptor for react router?

I Want to intercept when each route is called which is declared using react-router and append a query param to the end of it.

Reason to for this would be that there are set of query params that I need to append at the end of each route, however since I am currently working on a large code base I cannot look into each route and append it. Therefore if I can write some sought of an interceptor which is call every time a route is called and then append the query param there and pass on the request it would be ideal.

Is there such a feature in react-router ? I'm using react-router v4

like image 652
dushansilva Avatar asked Apr 09 '26 15:04

dushansilva


1 Answers

One way that I can think of is to "enhance" the history object that's passed into the Provider... You could make an enhancer of the public methods of that object and to add that functionality there, basically you would have to "enhance" the push and replace methods. Something more or less like this:

function pathInterceptor(path) {
  // TODO Your logic here
  // return an enhanced path that ensures that you have the
  // query string that you need
}

function historyEnhancer(originalHistory) {
  return {
    ...originalHistory,
    push: (path, ...args) =>
      originalHistory.push(pathInterceptor(path), ...args),
    replace: (path, ...args) =>
      originalHistory.replace(pathInterceptor(path), ...args),
  };
}

EDIT:

Have a look at this codesandbox with an example of this idea.

like image 79
Josep Avatar answered Apr 30 '26 01:04

Josep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!