diff --git a/front/app/organizations/page.tsx b/front/app/organizations/page.tsx index 58c3886c..bc7181ab 100644 --- a/front/app/organizations/page.tsx +++ b/front/app/organizations/page.tsx @@ -3,63 +3,43 @@ import Link from "next/link"; import React from "react"; import Layout from "../../components/UI/Layout"; import { Title } from "../../components/UI/Elements/Styles/Title"; -import { deleteOrganizationFromBackend, getUserOrganizations } from "../../services/orgs"; +import { deleteOrganizationFromBackend } from "../../services/orgs"; +import useSWR, { mutate } from "swr"; +import { swrFetcher } from "@services/utils/requests"; +import { getAPIUrl } from "@services/config"; const Organizations = () => { - const [userOrganizations, setUserOrganizations] = React.useState([]); - const [isLoading, setIsLoading] = React.useState(false); + const { data, error } = useSWR(`${getAPIUrl()}orgs/user/page/1/limit/10`, swrFetcher) - async function fetchUserOrganizations() { - const response = await getUserOrganizations(); - setUserOrganizations(response); - console.log(response); - setIsLoading(false); - } - - async function deleteOrganization(org_id:any) { + async function deleteOrganization(org_id: any) { const response = await deleteOrganizationFromBackend(org_id); - const newOrganizations = userOrganizations.filter((org:any) => org.org_id !== org_id); - setUserOrganizations(newOrganizations); + response && mutate(`${getAPIUrl()}orgs/user/page/1/limit/10`, data.filter((org: any) => org.org_id !== org_id)); } - - React.useEffect(() => { - setIsLoading(true); - fetchUserOrganizations(); - setIsLoading(false); - }, []); - - return ( Your Organizations{" "} <Link href={"/organizations/new"}> - <button>+</button> - </Link>
- {isLoading ? ( + {error &&

Failed to load

} + {!data ? (

Loading...

) : (
- {userOrganizations.map((org: any) => ( + {data.map((org: any) => (
-

{org.name}

- - +
))}
)} -
); }; diff --git a/front/services/utils/requests.ts b/front/services/utils/requests.ts index df32b5e3..b81b4dfe 100644 --- a/front/services/utils/requests.ts +++ b/front/services/utils/requests.ts @@ -12,3 +12,31 @@ export const RequestBody = (method: string, data: any) => { return options; }; +export const swrFetcher = async (url: string, body: any) => { + + // Create the request options + let HeadersConfig = new Headers({ "Content-Type": "application/json" }); + let options: any = { + method: "GET", + headers: HeadersConfig, + redirect: "follow", + credentials: "include", + }; + + // If there is a body, add it to the request options + if (body) { + options.body = JSON.stringify(body); + } + + // Fetch the data + const res = await fetch(url, options); + + // If the response is not in the 200 range, throw an error + if (!res.ok) { + const error = new Error("An error occurred while fetching the data."); + throw error; + } + + // Return the data + return res.json(); +};