react-router-dom useHistory() not working

Viewed 14485

The useHistory() hook is not working in my project. I have it in different components but none of them work. I am using "react-router-dom": "^5.2.0",

import {useHistory} from 'react-router-dom'

const history = useHistory()

const logout = () => {    
   toggleMenu()
   setUser(null)
   dispatch({type: 'LOGOUT'})
   history.push('/')
}

And also in action its not working

export const signin = (formdata, history, setError) => async (dispatch) => {
try {
    const {data} = await API.signIn(formdata)
    if(data.error){
        setError(data.message)
    }else{
        dispatch({type: SIGNIN, data})
        history.push('/dashboard')
    }

   } catch (error) {
    setError(error)
    console.log(error)
  }
}

Here is my router.js file

const Router = () => {
    const user = JSON.parse(localStorage.getItem('profile'))
    return (
       <BrowserRouter>
                <>
                    {user && <Navigation/>}
                    <Switch>
                        <Route path='/page-not-found' component={Auth}/>
                        <Route path='/' exact component={()=>((user && user.result) ? <Redirect to="/dasboard"/> : <Auth/>)} />
                        
                        <Route path='/dashboard' component={() => (user ? <Dashboard/> : <Redirect to='/'/>)} />
                        <Route path='/books-purchase' component={() => (user ? <BooksPage/> : <Redirect to='/' />)} />
                    
                    </Switch>
                </>
            
        </BrowserRouter>
      )
  }
7 Answers
  • For the version of react router dom less than 6.^

You can use useHistory() hook like your code is showing

  • For the latest version of react router dom greater than 6.^

You can use useNavigate() hook like this. You can also use without props

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

class Login extends Component {
  ....

  let navigate = useNavigate();

      navigate('/');
    
    .....

After some investigation, I found that there is a bug in react-router-dom version ^5.2.0. See this and this . I would suggest you to downgrade react-router-dom version to 4.10.1

Instead of useHistory, try useNavigate:

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

In my point of view, It doesn't need to downgrade react-router-dom, just use "useNavigate" hook instead of "useHistory" hook. For example if you also want to send some data to your dashboard page, you can use it like so:

import { useNavigate } from 'react-router-dom'

const FunctionalComponent = () => {
    const navigate = useNavigate();

    const TestHandler = (someData) => {
        navigate("/dashboard", {state: {someData: someData}});
        //and if you don't want to send any data use like so:
        //navigate("/dashboard");
    }
}

Finally, if you want to use that sent data for example in your dashboard page, you can do it like so:

import { useLocation } from 'react-router-dom'

export const Dashboard = () => {
    const location = useLocation();


    useEffect(() => {
        if (location.state.someData) {
            // "someData" is available here.
        }
    });

You can refer to this migration guide: https://reactrouter.com/docs/en/v6/upgrading/v5

i have same error, I forgot add type to button that working function. when i give type,problem was solved

Sometimes, if we call history in dialog or modal it shows error, pass the method to components

const methodTopass= () => {
    history.push("/route");
};

<componet methodTopass/>

left "react-router-dom": "^5.2.0",
add "history": "4.10.1", in to package.json
then use import { createBrowserHistory } from "history";
and
let hist = createBrowserHistory();
hist.push("/domoy");

Related