How To Fetch GitHub Repo From GitHub API With React.

This article is probably below beginner level, if you wouldn't mind learning from a tech newbie, then you're welcome.

Introduction

In this article, I will be giving a breakdown of how I fetched GitHub Repositories from my GitHub account. while at that, I should probably throw in how I set up my error boundary too. Do you know that little snitchy thing that tells you "Something went wrong" when there's an error in your react code? That's the error boundary.

Installations

I used Vite to scaffold react into my project.

npm create vite@latest *folder name* -- --template react
cd *foldername*
npm install

After the vite has been installed, I went ahead to install the error boundary.

npm install react-error-boundary

After the error boundary has been installed, it's now time to make my app go live so i can see what I am creating.

npm run dev

Error Boundary

According to the react documentation:

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

I went to my app.jsx component and wrapped the whole components with error boundary.

import { ErrorBoundary } from "react-error-boundary";
function App() {
  const navigate = useNavigate();
  return (
    <ErrorBoundary
      FallbackComponent={Fallback}
      onReset={() => {
        navigate("/");
      }}
    >
      <div className="container">
        Welcome to my app
      </div>
    </ErrorBoundary>
  );
}

My error boundary has a fallback component prop that receives a fallback component that renders when there is an error in my page.

function Fallback({ error, resetErrorBoundary }) {
  return (
    <div className="fallback">
      <p>Omoh!!! Something went wrong o</p>
      <p style={{ color: " rgb(189, 30, 30)" }}>{error.message}</p>
      <button onClick={resetErrorBoundary}>Back to Home</button>
    </div>
  );
}

export default Fallback;

Fetch GitHub Repo from GitHub And Paginating Them

To fetch my GitHub repositories from my GitHub account, I created a Repos component and did the following;

import { useEffect } from "react";
import { useState } from "react";
import { useErrorHandler } from "react-error-boundary";

function Repos() {
  const [repos, setRepos] = useState([]);
  const [loading, setLoading] = useState(false);
  const handleError = useErrorHandler();
  const navigate = useNavigate();
  const usersPerPage = 5;
  const [pages, setPages] = useState(1);
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(
          "https://api.github.com/users/*github username*/repos"
        );
        const data = await response.json();
        {
          console.log(data);
        }
        setRepos(data);
        setLoading(false);
      } catch (error) {
        handleError(error);
      }
    };
    fetchData();
  }, []);
  if (loading) return <h2>Loading...</h2>;
  return (
    <div>
      <h3 className="github">My 20 Github Repositories.</h3>
      <div className="repos-container">
        <div className="repos">
          {repos
            .slice((pages - 1) * usersPerPage, pages * usersPerPage)
            .map((repo, index) => {
              return (
                <div className="repo" key={repo.id}>
                  <Link to={repo.name}>{repo.name}</Link>
                  <h4>{repo.language}</h4>
                  <p>{repo.visibility}</p>
                </div>
              );
            })}
        </div>
        <div>
          Pages {pages} of {repos.length / usersPerPage}
        </div>
        <button
          disabled={pages <= 1}
          onClick={() => {
            setPages((p) => p - 1);
          }}
        >
          Prev
        </button>
        {Array.from(
          { length: Math.ceil(repos.length / usersPerPage) },
          (_, index) => index + 1
        ).map((btn) => (
          <button
            key={btn}
            className={pages === btn ? "active" : null}
            onClick={() => {
              setPages(btn);
            }}
          >
            {btn}
          </button>
        ))}
        <button
          disabled={pages >= repos.length / usersPerPage}
          onClick={() => {
            setPages((p) => p + 1);
          }}
        >
          Next
        </button>
      </div>
      <button className="btn2" onClick={() => navigate("/home")}>Back</button>
    </div>
  );
}

export default Repos;

Conclusion

Thank you for taking the time to go through my below beginner-level blog. I hope you learnt something.