From f58a1d127577b07bd849df85afd5e574eaec3a35 Mon Sep 17 00:00:00 2001 From: Andrew Lee Date: Thu, 8 Feb 2024 15:21:20 +0000 Subject: Turned GitHub projects into a component --- src/components/GitHubProjects.jsx | 75 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/components/GitHubProjects.jsx (limited to 'src/components/GitHubProjects.jsx') diff --git a/src/components/GitHubProjects.jsx b/src/components/GitHubProjects.jsx new file mode 100644 index 0000000..b54dc9f --- /dev/null +++ b/src/components/GitHubProjects.jsx @@ -0,0 +1,75 @@ +import { h } from 'preact'; +import { useState, useEffect } from 'preact/hooks'; + +const GitHubProjects = ({ username, isOrganization }) => { + const [repos, setRepos] = useState([]); + const [error, setError] = useState(null); + const [currentPage, setCurrentPage] = useState(1); + const reposPerPage = 10; + + useEffect(() => { + const fetchRepos = async () => { + const baseUrl = 'https://api.github.com'; + const url = isOrganization + ? `${baseUrl}/orgs/${username}/repos` + : `${baseUrl}/users/${username}/repos`; + + try { + const response = await fetch(url); + const data = await response.json(); + + if (response.ok) { + if (Array.isArray(data)) { + setRepos(data.filter(repo => !repo.fork)); + } else { + console.error('Unexpected data format:', data); + setError('Unexpected data format'); + setRepos([]); + } + } else { + console.error('API error:', data); + setError(data.message); + setRepos([]); + } + } catch (err) { + console.error('Failed to fetch projects:', err); + setError(err.message); + setRepos([]); + } + }; + + fetchRepos(); + }, [username, isOrganization]); // Don't forget to include dependencies + + // Get current repos + const indexOfLastRepo = currentPage * reposPerPage; + const indexOfFirstRepo = indexOfLastRepo - reposPerPage; + const currentRepos = repos.slice(indexOfFirstRepo, indexOfLastRepo); + + // Change page + const nextPage = () => setCurrentPage(currentPage + 1); + const prevPage = () => setCurrentPage(currentPage - 1); + + return ( +
+ {error &&
{error}
} +
+ {currentRepos.map((repo) => ( +
+

{repo.name}

+

{repo.description}

+ +
+ ))} +
+
+ {currentPage > 1 && } + {currentPage < Math.ceil(repos.length / reposPerPage) && } +
+
+ ); +}; + +export default GitHubProjects; \ No newline at end of file -- cgit v1.2.3