diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts new file mode 100644 index 0000000000000000000000000000000000000000..0479313fa68645acd8ff0ef33ff64e1b24e9ee6d --- /dev/null +++ b/src/hooks/useAuth.ts @@ -0,0 +1,28 @@ +import { isAuthenticated } from 'api/isAuthenticated'; +import { useEffect, useState } from 'react'; + +/** + * Custom hook that uses the call is_authenticated. + * {@link isAuthenticated} + * + * @returns {boolean | null} isAuth: true if user is authenticated, false otherwise or null if the request has not finished. + */ +export const useAuth = (): [ + boolean, + React.Dispatch<React.SetStateAction<boolean>>, +] => { + let isMounted = true; + const [isAuth, setIsAuth] = useState<boolean>(false); + useEffect(() => { + isAuthenticated().then((state) => { + if (isMounted) { + setIsAuth(state); + } + }); + + return () => { + isMounted = false; + }; + }, []); + return [isAuth, setIsAuth]; +}; diff --git a/src/hooks/useCookie.ts b/src/hooks/useCookie.ts new file mode 100644 index 0000000000000000000000000000000000000000..d2fc2eaad555d1a00ab5dfefe43a64103d6f5b22 --- /dev/null +++ b/src/hooks/useCookie.ts @@ -0,0 +1,27 @@ +import { fetchCookie } from 'api/fetchCookie'; +import { useCallback, useEffect, useState } from 'react'; + +/** + * Custom hook that return csrf cookie fetched from server. + * + * @return cookie + */ +export const useCookie = (): string => { + const [cookie, setCookie] = useState(''); + + const askCookie = useCallback(() => { + let isMounted = true; + if (isMounted) + fetchCookie().then((cookieResponse) => setCookie(cookieResponse)); + + return () => { + isMounted = false; + }; + }, []); + + useEffect(() => { + askCookie(); + }, [askCookie]); + + return cookie; +}; diff --git a/src/hooks/useRole.ts b/src/hooks/useRole.ts new file mode 100644 index 0000000000000000000000000000000000000000..785a9793d68e38bc9aad578169aa195a0d84f9fc --- /dev/null +++ b/src/hooks/useRole.ts @@ -0,0 +1,24 @@ +import { getRole } from 'api/getRole'; +import { useEffect, useState } from 'react'; + +export const useRole = (): [ + string, + React.Dispatch<React.SetStateAction<string>>, +] => { + const [role, setRole] = useState(''); + + useEffect(() => { + let isMounted = true; + // Initialize asking the server if this session is already logged in. + + getRole().then((responseRole) => { + if (isMounted) { + setRole(responseRole); + } + }); + return () => { + isMounted = false; + }; + }, []); + return [role, setRole]; +};