Skip to content

Commit

Permalink
logout
Browse files Browse the repository at this point in the history
logout function
  • Loading branch information
u0509421 committed Jan 12, 2025
1 parent 28e2fc0 commit d621514
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
12 changes: 11 additions & 1 deletion frontend/src/components/sidebar/LogoutButton.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
import { BiLogOut } from "react-icons/bi";
import useLogout from "../../hooks/useLogout";

const LogoutButton = () => {
const { loading, logout } = useLogout();

return (
<div className="mt-auto">
<BiLogOut className="w-6 h-6 text-white cursor-pointer" />
{!loading ? (
<BiLogOut
className="w-6 h-6 text-white cursor-pointer"
onClick={logout}
/>
) : (
<span className="loading loading-spinner"></span>
)}
</div>
);
};
Expand Down
33 changes: 33 additions & 0 deletions frontend/src/hooks/useLogout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React from "react";
import { useAuthContext } from "../context/AuthContext";
import toast from "react-hot-toast";

const useLogout = () => {
const [loading, setLoading] = React.useState(false);
const { setAuthUser } = useAuthContext();

const logout = async () => {
setLoading(true);
try {
const res = await fetch("/api/auth/logout", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const data = await res.json();
if (data.error) {
throw new Error(data.error);
}
localStorage.removeItem("chat-user");
setAuthUser(null);
} catch (error) {
toast.error(error.message);
} finally {
setLoading(false);
}
};
return { loading, logout };
};

export default useLogout;

0 comments on commit d621514

Please sign in to comment.