From cc231dbfaad1f5adbff021cd6270ad7db2f38ba3 Mon Sep 17 00:00:00 2001 From: Peter KW Date: Wed, 20 Mar 2024 00:14:23 +0100 Subject: [PATCH] Component for getting all users --- frontend/src/Components/GetAllUsers.tsx | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 frontend/src/Components/GetAllUsers.tsx diff --git a/frontend/src/Components/GetAllUsers.tsx b/frontend/src/Components/GetAllUsers.tsx new file mode 100644 index 0000000..73ad244 --- /dev/null +++ b/frontend/src/Components/GetAllUsers.tsx @@ -0,0 +1,35 @@ +import { Dispatch, useEffect } from "react"; +import { api } from "../API/API"; + +/** + * Gets all usernames in the system and puts them in an array + * @param props - A setStateAction for the array you want to put users in + * @returns {void} Nothing + * @example + * const [users, setUsers] = useState([]); + * GetAllUsers({ setUsersProp: setUsers }); + */ +function GetAllUsers(props: { + setUsersProp: Dispatch>; +}): void { + const setUsers: Dispatch> = props.setUsersProp; + useEffect(() => { + const fetchUsers = async (): Promise => { + try { + const token = localStorage.getItem("accessToken") ?? ""; + const response = await api.getAllUsers(token); + if (response.success) { + setUsers(response.data ?? []); + } else { + console.error("Failed to fetch users:", response.message); + } + } catch (error) { + console.error("Error fetching users:", error); + } + }; + + void fetchUsers(); + }, [setUsers]); +} + +export default GetAllUsers;