Next.js Discord

Discord Forum

Weird issue with client-side routing and custom hook.

Answered
Cairn Terrier posted this in #help-forum
Open in Discord
Cairn TerrierOP
I have a layout that surrounds all protected pages. then each page contains it's specific components. on some of these pages I use a hook to perform further auth checks based on permissions. I have used this same hook in a previous project using the same version of Next and no issues. Except in this project when using the hook it causes the Links to stop working as expected.

When clicking a link in the sidebar Component the adress bar changes but the content of the page stays the same. If I refresh then it changes to the correct content for that route. If I remove the Auth hook everything goes back to working as normal.

import { useEffect, useState } from "react";
import { RoleInt as Role, UserInt as User } from "../utils/types";

export function useAuthorization(
  user: User | null,
  allowedRoles: string[] | null,
  key: string
) {
  const [isAuthorized, setIsAuthorized] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  useEffect(() => {
    // Helper function to check if a role has any allowed permission
    const hasAllowedPermission = (role: Role) => {
      return role.permissions.some((permission) =>
        allowedRoles?.includes(permission.name)
      );
    };

    if (!user) {
      setIsAuthorized(false);
      setIsLoading(false);
      return;
    }

    if (!allowedRoles || allowedRoles.length === 0) {
      setIsAuthorized(true);
      setIsLoading(false);
      return;
    }

    setIsAuthorized(user.roles.some(hasAllowedPermission));
    setIsLoading(false);
  }, [allowedRoles, key, user]);

  return { isAuthorized, isLoading };
}
This is the hook

  const { isAuthorized: canDelete } = useAuthorization(
    user,
    ['SENIORADMIN', 'ADMIN', 'DELETE_RANKS'],
    'deleteRank'
  );
And this is how it's implemented

Any advice/suggestions?
Answered by Cairn Terrier
My Issue was solved. but in no way that is helpful to anyone else who may have a similar issue. My fix involved cloning the project that did work. removing and replacing all the code from my old project and then upgrading certain packages in line with the needs of my new project. What the fix was exactly, is a mystery to me.
View full answer

1 Reply

Cairn TerrierOP
My Issue was solved. but in no way that is helpful to anyone else who may have a similar issue. My fix involved cloning the project that did work. removing and replacing all the code from my old project and then upgrading certain packages in line with the needs of my new project. What the fix was exactly, is a mystery to me.
Answer