diff --git a/src/components/UserControls.js b/src/components/UserControls.js index 9c4f9eb..67a9903 100644 --- a/src/components/UserControls.js +++ b/src/components/UserControls.js @@ -1,24 +1,41 @@ -import React from "react"; +import React, { useRef } from "react"; import '../css/components/UserControls.css'; import { useLoginContext } from "../structures/UserContext"; +import ClickDetector from "../util/ClickDetector"; +import { clearSession, post } from "../util/Util"; const UserControls = () => { - const [user] = useLoginContext(); + const [user, updateUser] = useLoginContext(); + const detailsRef = useRef(); if (!user) return; - return
- - Hello {user.displayName} - - -
-

Profile

-
-

Logout

-
-
; + const logOut = async () => { + const response = await post('/api/logout'); + if (response.status === 200) { + clearSession(); + updateUser(); + } + }; + + return { + if (detailsRef.current) detailsRef.current.removeAttribute('open'); + }}> +
+ + Hello {user.displayName} + + + +
+

Profile

+
+

Logout

+
+ +
+
; }; diff --git a/src/util/ClickDetector.js b/src/util/ClickDetector.js new file mode 100644 index 0000000..8f5b351 --- /dev/null +++ b/src/util/ClickDetector.js @@ -0,0 +1,35 @@ +import React, { useEffect, useRef } from "react"; + +const alerter = (ref, callback) => { + useEffect(() => { + + const listener = (event) => { + if (ref.current && !ref.current.contains(event.target)) { + return callback(); + } + }; + + document.addEventListener('mousedown', listener); + + return () => { + document.removeEventListener('mousedown', listener); + }; + + }, [ref]); +}; + +// Component wrapper to enable listening for clicks outside of the given component +const ClickDetector = ({ children, callback }) => { + + const wrapperRef = useRef(null); + alerter(wrapperRef, callback); + + return ( +
+ {children} +
+ ); + +}; + +export default ClickDetector; \ No newline at end of file