URL gets changed after doing history(dot)push but history(dot)location(dot)pathname remains same in react

134 Views Asked by At

Navigation is working perfectly when I click. But after registering a user, when I do history.push('/login') then it changes the URL in the URL bar and goes to the login page, but if I console.log(history.location.pathname) then still the pathname remains to /register and active link is highlighted in register nav link even after going to the login page. How to fix this. Even I tried passing history from react-router using

const history = createBrowserHistory()
<Route render={(props)=><Navbar {...props} history={history}/>}/>

It didn't work. So, how to fix it?

export const registerUser = (fields, history) => async dispatch => {
    const config = {
        headers:{
            'Content-Type': 'application/json'
        }
    }
    const body = JSON.stringify(fields)

    try{
        dispatch(createAction(LOADING_TRUE))
        const response = await axios.post(`${api}/signup`, body, config)
        dispatch(createAction(USER_SUCCESS, response.data))
        dispatch(setGlobalMessage('positive', 'User registered successfully'))
        dispatch(createAction(LOADING_FALSE))
        history.push('/login')
    }catch(error){
        dispatch(createAction(LOADING_FALSE))
        console.log(error.response);
        error.response.data.errors 
        ? dispatch(createAction(USER_FAILURE, error.response.data))
        : dispatch(setGlobalMessage('negative', error.response.data.msg))
    }
}
1

There are 1 best solutions below

0
On

Before you route to the page, you can clear history by

window.history.replaceState(null, '')

more info here