From 1646971a726ff63e59b82e0cfff0e7f160726537 Mon Sep 17 00:00:00 2001 From: aldbr Date: Fri, 29 Sep 2023 15:26:54 +0200 Subject: [PATCH] feat: add a hooks folder --- src/components/JobDataGrid.tsx | 20 +++++++------------- src/hooks/jobs.tsx | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 13 deletions(-) create mode 100644 src/hooks/jobs.tsx diff --git a/src/components/JobDataGrid.tsx b/src/components/JobDataGrid.tsx index 21a993e9..ec7717f6 100644 --- a/src/components/JobDataGrid.tsx +++ b/src/components/JobDataGrid.tsx @@ -1,7 +1,6 @@ "use client"; import { DataGrid } from "@mui/x-data-grid"; -import { useOidcAccessToken } from "@axa-fr/react-oidc"; -import useSWR from "swr"; +import { useJobs } from "@/hooks/jobs"; const columns = [ { field: "JobID", headerName: "Job ID", width: 70 }, @@ -16,22 +15,17 @@ const columns = [ * @returns a DataGrid displaying details about jobs */ export function JobDataGrid() { - const { accessToken } = useOidcAccessToken(); + const { data, error, isLoading } = useJobs(); - // TODO: move fetcher to make it usable from other places - const fetcher = (params: string[]) => { - const [path] = params; - return fetch(process.env.NEXT_PUBLIC_DIRACX_URL + path, { - method: "POST", - headers: { Authorization: "Bearer " + accessToken }, - }).then((res) => res.json()); - }; - const { data, error } = useSWR(["/jobs/search?page=0&per_page=100"], fetcher); + if (isLoading) { + return
Loading...
; + } if (error) { return
An error occurred while fetching jobs.
; } - if (!data || data.length == 0) { + + if (!data || data.length === 0) { return
No job submitted.
; } diff --git a/src/hooks/jobs.tsx b/src/hooks/jobs.tsx new file mode 100644 index 00000000..9e724d47 --- /dev/null +++ b/src/hooks/jobs.tsx @@ -0,0 +1,26 @@ +import { useOidcAccessToken } from "@axa-fr/react-oidc"; +import useSWR from "swr"; + +const fetcher = (args: any[]) => { + const [url, accessToken] = args; + + return fetch(url, { + method: "POST", + headers: { Authorization: "Bearer " + accessToken }, + }).then((res) => { + if (!res.ok) throw new Error("Failed to fetch jobs"); + return res.json(); + }); +}; + +export function useJobs() { + const { accessToken } = useOidcAccessToken(); + const url = `${process.env.NEXT_PUBLIC_DIRACX_URL}/jobs/search?page=0&per_page=100`; + const { data, error } = useSWR([url, accessToken], fetcher); + + return { + data, + error, + isLoading: !data && !error, + }; +}