Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove query param with react hooks?

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?

like image 593
Seth McClaine Avatar asked May 26 '20 21:05

Seth McClaine


People also ask

How do I get query params in react router v6?

First you'll need to import the useSearchParams hook and destruct the return value to get the current value of, React Router v6 calls these the “search params” due to them existing on the window.

How do I redirect in react?

The Redirect component was usually used in previous versions of the react-router-dom package to quickly do redirects by simply importing the component from react-router-dom and then making use of the component by providing the to prop, passing the page you desire to redirect to.


Video Answer


2 Answers

For React Router V6 and above, see the answer below.


Original Answer:

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).

like image 165
Ajeet Shah Avatar answered Oct 17 '22 04:10

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>
}
like image 4
Vaelyr Avatar answered Oct 17 '22 03:10

Vaelyr