Search code examples
reactjsreact-class-based-component

Filtering content based on query string using React Js


We have a simple react app.. Data is coming from an api and stored in the state. Then we use a map function to render the data. And use sort and filter functions to manipulate the data.

Now, we are trying to associate the filter information with the URL by using the query string. So that, on sharing the page URL, filter data is also passed along with it.

We are updating the query string using the link tag of 'react-router-dom' library

<Link to='/pagePath?queryStringKey=queryStringValue'> Link Content </Link>

Now, how to listen to query string change? componentDidMount runs only once when the component is mounted. But when the query string is changed using the Link tag, componentDidMount do not run. And if we listen from render function then it gives this error.

Error: Maximum update depth exceeded. 

What is the right way to listen/detect the query string change?


Solution

  • the reason you are getting that error is because you're listening in the render function. React mounts, renders, listens to the query string, re-renders again, remounts, re-listens etc. until you have exceeded the max update depth

    if componentDidMount isn't working, consider using componentDidUpdate this will update every time the component updates