Skip to content

Commit

Permalink
Refactor data fetching and loading logic
Browse files Browse the repository at this point in the history
  • Loading branch information
WCY-dt committed Apr 29, 2024
1 parent f694fe0 commit 318ddfb
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 26 deletions.
12 changes: 11 additions & 1 deletion src/components/clusters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import LinkCard from '../components/linkCard';
import ClearFilter from '../utils/clearFilter';
import { fetchAndFilterData } from '../services/dataFetcher';
import '../styles/clusters.css';
import '../styles/loading.css';

interface ClustersProps {
dataKey: string;
Expand All @@ -13,11 +14,20 @@ interface ClustersProps {
function Clusters({ dataKey, searchTerm, setSearchTerm }: ClustersProps) {
const [clusters, setClusters] = useState<ClusterProps[]>([]);
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);

useEffect(() => {
fetchAndFilterData(dataKey, true, selectedCategory, searchTerm, setClusters);
setIsLoading(true);
fetchAndFilterData(dataKey, true, selectedCategory, searchTerm, setClusters)
.finally(() => setIsLoading(false));
}, [dataKey, selectedCategory, searchTerm]);

if (isLoading) {
return (
<div className="loading"></div>
);
}

return (
<>
<h1 className="Clusters-title">{dataKey}</h1>
Expand Down
2 changes: 1 addition & 1 deletion src/components/content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ function Content({ routes, searchTerm, setSearchTerm }: ContentProps) {
<div className="App-content">
<Routes>
<Route path="/"
element={<Cluster dataKey="techniques" searchTerm={searchTerm} setSearchTerm={setSearchTerm} />}
element={<Cluster dataKey={routes[Object.keys(routes)[0]]} searchTerm={searchTerm} setSearchTerm={setSearchTerm} />}
/>
{Object.entries(routes).map(([path, element]) => (
<Route path={path}
Expand Down
25 changes: 18 additions & 7 deletions src/routers/router.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { BrowserRouter } from 'react-router-dom';

import { fetchCollection } from '../services/collectionFetcher';
import Header from '../components/header';
import Content from '../components/content';
import Footer from '../components/footer';

import '../styles/loading.css';

function Router() {
const [searchTerm, setSearchTerm] = useState('');

const routes = {
"/tech": "techniques",
"/opi": "opinions",
"/ins": "inspirations"
};
const [isLoading, setIsLoading] = useState<boolean>(true);

const [routes, setRoutes] = useState({});
useEffect(() => {
setIsLoading(true);
fetchCollection(setRoutes)
.finally(() => setIsLoading(false));
}, []);

if (isLoading) {
return (
<div className="loading"></div>
);
}

return (
<BrowserRouter>
Expand Down
24 changes: 24 additions & 0 deletions src/services/collectionFetcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export function fetchCollection(setRoutes: (value: {}) => void) {
return new Promise(async (resolve, reject) => {
const api = "https://api.mind.ch3nyang.top";
let url = `${api}/collection`;

try {
const response = await fetch(url, { method: 'GET' });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: string[] = await response.json();
let routes: { [key: string]: string } = {};
data.forEach((collection) => {
routes[`/${collection.toLowerCase()}`] = collection;
});
setRoutes(routes);
resolve(undefined);
} catch (e) {
console.error(`Fetch failed: ${(e as Error).message}`);
console.error(`Failed URL: ${url}`);
reject(e);
}
});
}
35 changes: 18 additions & 17 deletions src/services/dataFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,31 @@ export function fetchAndFilterData(
searchTerm: string = '',
setClusters: (value: ClusterProps[]) => void
) {
const api = "https://api.mind.ch3nyang.top";
let url = `${api}/card?collection=${dataKey}`;
if (selectedCategory) {
url += `&category=${selectedCategory}`;
}
if (searchTerm) {
url += `&search=${searchTerm}`;
}
return new Promise(async (resolve, reject) => {
const api = "https://api.mind.ch3nyang.top";
let url = `${api}/card?collection=${dataKey}`;
if (selectedCategory) {
url += `&category=${selectedCategory}`;
}
if (searchTerm) {
url += `&search=${searchTerm}`;
}

fetch(url, { method: 'GET' })
.then(response => {
try {
const response = await fetch(url, { method: 'GET' });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
let data = await response.json();
if (isRandom) {
data = data.sort(() => Math.random() - 0.5);
}
setClusters(data);
})
.catch(e => {
console.error(`Fetch failed: ${e.message}`);
resolve(undefined);
} catch (e) {
console.error(`Fetch failed: ${(e as Error).message}`);
console.error(`Failed URL: ${url}`);
});
reject(e);
}
});
}
24 changes: 24 additions & 0 deletions src/styles/loading.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
.loading {
border: 16px solid #f3f3f3;
border-radius: 50%;
border-top: 16px solid black;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}

@keyframes spin {
0% {
transform: rotate(0deg);
}

100% {
transform: rotate(360deg);
}
}

0 comments on commit 318ddfb

Please sign in to comment.