I am updating a React with redux app to work with react-router-dom
v6.
In the application, I have a helper file used for browser history:
_helpers.history.ts
import { createBrowserHistory } from 'history';
export const history = createBrowserHistory();
I used this in my user.actions.js file to navigate users to new views after login, registration, etc.
user.actions.js
import { history } from '../_helpers';
export const userActions = {
login,
logout,
register,
getAll,
delete: _delete
};
function login(username, password, from) {
return dispatch => {
dispatch(request({ username }));
userService.login(username, password)
.then(
user => {
dispatch(success(user));
history.push('/dashboard');
},
error => {
dispatch(failure(error.toString()));
dispatch(alertActions.error(error.toString()));
}
);
};
I replaced createBrowserHistory
with useNavigate
from react-router-dom:
history.js (updated)
import { useNavigate } from "react-router-dom";
export const history = useNavigate();
and in user.actions.js, history.push('/dashboard');
was replaced with navigate(dashboard)
However, trying to do this produces the following error:
ERROR in [eslint]
src/_helpers/history.js
Line 3:24: React Hook "useNavigate" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
I also use the _helpers.history.js in my App.js file: APP.JS
import { history } from "./_helpers";
function App() {
return (
<>
<Routes history={history}>
{/* Public Pages */}
<Route exact path="/" element={<HomePage />} />
I've looked at a couple of S/O answers but they are all related to applications using functional components. What would be the correct method to update the helper file in this case?