Last active
August 17, 2024 06:06
-
-
Save sasial-dev/fbdbb06c2a32aa2f08e827bb84bb8efa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from "@rbxts/react"; | |
import { useSelector } from "@rbxts/react-reflex"; | |
interface RouteProps extends React.PropsWithChildren { | |
path?: string; | |
visible?: boolean; | |
mount?: () => Promise<void>; | |
unmount?: () => Promise<void>; | |
} | |
export = React.memo<RouteProps>((props) => { | |
const currentRoute = useSelector((state) => state.gui.menu.route); | |
const isOpen = (props.path && props.path === currentRoute) || props.visible || false; | |
const [shouldRender, setShouldRender] = useState(isOpen); | |
useEffect(() => { | |
// on mount only | |
if (isOpen === true && props.mount) { | |
props.mount(); | |
} | |
}, []); | |
// we can't use await as we cannot yield in a useEffect | |
const updateShouldRender = () => { | |
if (shouldRender !== isOpen) { | |
if (isOpen === true) { | |
if (props.mount) { | |
props.mount().then(() => setShouldRender(isOpen)); | |
} else { | |
setShouldRender(isOpen); | |
} | |
} else if (props.unmount) { | |
props.unmount().then(() => setShouldRender(isOpen)); | |
} else { | |
setShouldRender(isOpen); | |
} | |
} | |
}; | |
useEffect(updateShouldRender, [isOpen]); | |
return shouldRender && props.children; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment