Home > Software design >  Why wouldn't my Sidebar open when calling a function from my custom hook
Why wouldn't my Sidebar open when calling a function from my custom hook

Time:05-30

I have this piece of code of mine :

My Custom Hook :

export const useSidebar = () => {
  const [showSidebar, setShowSidebar] = useState(false);

  const toggleSidebar = useCallback(() => {
    setShowSidebar(!showSidebar);
  }, [showSidebar]);

  return [showSidebar, toggleSidebar] as const;
};

My Sidebar :

export const Sidebar = () => {
  const [showSidebar, toggleSidebar] = useSidebar();

  return (
    <aside
      className={`top-0 right-0 w-[35vw] bg-blue-600  p-10 pl-20 text-white fixed h-full  ease-in-out duration-300 z-panel ${
        showSidebar ? 'translate-x-0 ' : 'translate-x-full'
      }`}
    >
      <button
        className="flex text-4xl text-white items-center cursor-pointer fixed right-10 top-6 z-50"
        onClick={() => toggleSidebar()}
      >
        x
      </button>

      <h3 className="mt-20 text-4xl font-semibold text-white">I am a sidebar</h3>
    </aside>
  );
};

When I call toggleSidebar() from my hook, my sidebar doesn't show up. The debugger indicates that showSidebar is always false.

Could you point to me what I'm doing wrong ?

Many thanks.

Run on Stackblitz

CodePudding user response:

Maybe It can be help

  const toggleSidebar = useCallback(() => {
    setShowSidebar(!showSidebar);
  }, [showSidebar]);

I think that the problem is dependencies

CodePudding user response:

Ok, my mistake I could not use hooks for that, so I went with a context.

export type SidebarContextType = {
  isVisible: boolean;
  toggleSidebar: () => void;
};

export const SidebarContext = createContext<SidebarContextType | null>(null);

export const SidebarProvider = ({ children }: { children: any }) => {
  const [isVisible, setIsVisible] = useState(false);
  const toggleSidebar = useCallback(() => {
    console.log('--', !isVisible);
    setIsVisible(!isVisible);
  }, [isVisible]);

  return <SidebarContext.Provider value={{ isVisible, toggleSidebar }}>{children}</SidebarContext.Provider>;
};
  • Related