0

Unable to efficiently get & set url query params in React. The app is using react router v4 and hooks such as useHistory, useLocation are not available. I cannot update the react router version since the app is a large production app.

On every feature of the app there are various filters like startDate, endDate and so on. I need a way to:

  1. Check whether any query params are being passed on the initial mount => can be done in useEffect
  2. on changing state of any filter such as startDate or endDate, the url param should change as well.

Currently what I've tried is:

// Init
React.useEffect(() => {
    const params = new URLSearchParams(location.search);
    const startDateParam = params.get('startDate');
    const endDataParam = params.get('endDate');
    const isDog = params.get('isDog'); //example

    if (startDateParam) setStartDate(startDateParam);
    else {
      params.set('startDate', startDate || '');
    } 

    if (endDateParam) setEndDate(endDateParam);
    else {
      params.set('endDate', endDate || '');
    }
},[])

React.useEffect(() => {
   const params = new URLSearchParams(location.search);
   const startDateParam = params.set('startDate', startDate);
   const endDataParam = params.set('endDate', endDate);
},[startDate, endDate]);

const [startDate, setStartDate] = useState(
    moment()
      .subtract(30, 'days')
      .format('YYYY-MM-DD')
  );
const [endDate, setEndDate] = useState(moment().format('YYYY-MM-DD'));

But this is not changing the url the I expect it to.

I need help with changing the url in my current implementation or a completely new (efficient) implementation

  • I think this link will help you to solve your query https://stackoverflow.com/questions/40161516/how-do-you-programmatically-update-query-params-in-react-router – sodhankit May 17 '22 at 10:29

0 Answers0