I learn React and JavaScript and I'm really new to this and now the React router V6. I have a method that is called from two location and wanted to create a util function to handle this.
It looks like this:
import { useNavigate } from 'react-router-dom';
import * as ROLES from '../../../constants/roles';
export default function dashboardNavigater() {
const { authUser } = this.props;
const navigate = useNavigate();
if (authUser) {
if (authUser.roles.includes(ROLES.ANON)) {
navigate('/app/login');
} else if (authUser.roles.includes(ROLES.USER) || authUser.roles.includes(ROLES.ADMIN)) {
const view = localStorage.getItem('currentDashBoardView');
// Here if user has used nav menu earlier then that last view is loaded
if (view) navigate(view);
// or default to dash
else navigate('/app/dashboard');
}
}
}
But I get this error:
Line 6:19: React Hook "useNavigate" is called in function "dashboardNavigater" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
How can I fix/refactor this so I can use this useNavigate()
I wanted to use this util function like this:
import React from 'react';
import styled from 'styled-components';
import WithDashboardNavigate from '../../session/WithDashboardNavigate';
import dashboardNavigater from '../DashboardLayout/NavBar/DashboardNavigater';
function SignedInButton({ onDashboard }) {
function openDashboard() {
dashboardNavigater();
}
return (
<div>
<Button className="button is-large" onClick={openDashboard}>
<span className="icon is-medium">
<i className="fas fa-user" />
</span>
</Button>
</div>
);
}