feat: init swr usage

This commit is contained in:
swve 2023-01-24 20:59:25 +01:00
parent 504128d4c9
commit cad10078ae
2 changed files with 39 additions and 31 deletions

View file

@ -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 (
<Layout>
<Title>
Your Organizations{" "}
<Link href={"/organizations/new"}>
<button>+</button>
</Link>
</Title>
<hr />
{isLoading ? (
{error && <p>Failed to load</p>}
{!data ? (
<p>Loading...</p>
) : (
<div>
{userOrganizations.map((org: any) => (
{data.map((org: any) => (
<div key={org.org_id}>
<Link href={`/org/${org.slug}`}>
<h3>{org.name}</h3>
</Link>
<button onClick={() => deleteOrganization(org.org_id)}>
Delete
</button>
<button onClick={() => deleteOrganization(org.org_id)}>Delete</button>
</div>
))}
</div>
)}
</Layout>
);
};

View file

@ -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();
};