I upgraded the REACT ROUTER DOM TO V6 from V5 I use REDUX and I have a general function called CHANGE ROUTE within the COMMON.ACTION Until now I used the HISTORY.PUSH and after the update, I need to change it to USE NAVIGATE but every time I change it I get the following error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
now I know that I break the hooks rules but I don't know why as changeRoute is a function what I'm I doing wrong?
Thanks for your help
this is my APP that used Navigation component:
return (
<Site onClick={(e) => handleClick(e)}>
<Navigation />
<SnackbarContentWrapper/>
<AppLevelComponents/>
</Site>
);
this is Navigation.js:
const Login = lazy(() => import("../../pages/login/Login"));
const Navigation = () => {
const fallback = <WithFullScreenLayout><Loader/></WithFullScreenLayout>;
return (
<Suspense fallback={fallback}>
<Routes>
<Route path="/login" element={<Login />}/>
</Routes>
</Suspense>
)
};
export default Navigation;
this is my chagnRoute function in common.action:
export const changeRoute = (route) => (dispatch) => {
const nav = useNavigate();
commonService.changeRoute(`${window.location.pathname}${window.location.search}`);
if (route !== '' && route !== '/') { // to prevent looping
nav(route);
}
dispatch({
type: CHANGE_ROUTE,
payload: route
});
};
this is how I used it in other components:
dispatch(changeRoute("/blabla"))
before the upgrade to router dom v6 its works like this in commom.action and evreything works OK:
export const changeRoute = (route) => (dispatch) => {
const nav = useNavigate();
commonService.changeRoute(`${window.location.pathname}${window.location.search}`);
if (route !== '' && route !== '/') { // to prevent looping
history.push(route);
}
dispatch({
type: CHANGE_ROUTE,
payload: route
});
};
Your changeRoute
is a javascript function, not a React function component
The rules of hooks say: Only Call Hooks from React Functions Don’t call Hooks from regular JavaScript functions.
This means you can't call useNavigate
inside changeRoute
Instead, you can pass nav
to changeRoute
as a parameter like this
dispatch(changeRoute("/blabla", useNavigation()))
But you have to make sure to call this dispatch only inside React function components