Source:  Twitter logo

I know we can replace query params in component based classes doing something along the lines of:

  componentDidMount() {       
    const { location, replace } = this.props;   

    const queryParams = new URLSearchParams(location.search);   
    if (queryParams.has('error')) { 
      this.setError(    
        'There was a problem.'  
      );    
      queryParams.delete('error');  
      replace({ 
        search: queryParams.toString(), 
      });   
    }   
  }

Is there a way to do it with react hooks in a functional component?

Yes, you can use useHistory & useLocation hooks from react-router:


import React, { useState, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'

export default function Foo() {
  const [error, setError] = useState('')

  const location = useLocation()
  const history = useHistory()

  useEffect(() => {
    const queryParams = new URLSearchParams(location.search)

    if (queryParams.has('error')) {
      setError('There was a problem.')
      queryParams.delete('error')
      history.replace({
        search: queryParams.toString(),
      })
    }
  }, [])

  return (
    <>Component</>
  )
}

As useHistory() returns history object which has replace function which can be used to replace the current entry on the history stack.

And useLocation() returns location object which has search property containing the URL query string e.g. ?error=occurred&foo=bar" which can be converted into object using URLSearchParams API (which is not supported in IE).

55 users liked answer #0dislike answer #055
Ajeet Shah profile pic
Ajeet Shah

Use useSearchParams hook.

import {useSearchParams} from 'react-router-dom';

export const App =() => {
  const [searchParams, setSearchParams] = useSearchParams();

  const removeErrorParam = () => {
    if (searchParams.has('error')) {
      searchParams.delete('error');
      setSearchParams(searchParams);
    }
  }

  return <button onClick={removeErrorParam}>Remove error param</button>
}
2 users liked answer #1dislike answer #12
Vaelyr profile pic
Vaelyr

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).