How I did an API fetch from my GitHub portfolio

How I did an API fetch from my GitHub portfolio

Made with React.js

As an assignment from one of the Biggest tech schools in Africa (AltSchool), I was told to:

  • Implement an API fetch of my GitHub portfolio

  • Show a page with a list of all my repositories on GitHub(the page should implement pagination for the repo list)

  • Create another page showing data for a single repo clicked from the list of repos using nested routes while using all the necessary tools in react.

  • Implement the proper SEO, Error Boundary (show a page to test the error boundary) and 404 pages. Good UI and Designs are important.

At first, this assignment looked complex because I had not worked with APIs before and was still imperfect with React. But thankfully Google, Youtube, and Starkoverflow among other sources existed.

The first step was understanding what was needed of me and proceeded to install my react app with npx create-react-app github-ass using VScode text editor.

Next, I created the contactMe.js(for the contact me page), Home.js (homepage), Notfound.js(Page shown when a wrong route is accessed), Repositories.js (page containing the GitHub repo), pagenation.js (gives paging to the list of the repo), profile.js (styling of the fetched data)components. I also installed some dependencies for functionality, namely:
react-helmet react-router-dom react-error-boundary react-icons tailwindcss

Fetching GitHub API

To fetch data from the GitHub API in a React app, you can use the fetch function, which is a global function available in modern browsers for making HTTP requests. Here is an example of how you can use fetch to get data from the GitHub API and display the name of the user's repository:

import React, { useState, useEffect } from 'react';

const [items, setItems] = useState([]);
useEffect(() => {
      const fetchRepos = async () => {
        const res = await fetch(
          `https://api.github.com/users/udofa18/repos`
        )
        const data = await res.json()
        setItems(data)



        }
         fetchRepos() 
    }, []);
return (
    <div>
      {items.map(item => (
        <h2 key={item.id}>{item.name}</h2>
      ))}
    </div>
  );
}

Implementing Pagination

Here is a simple way to implement pagination in a React application:

  1. Create a component for the pagination buttons. This component will render a button for each page, and the buttons should be disabled if the user is on the first or last page.

  2. In the component that displays the data, create a state variable to track the current page.

  3. When the component mounts, fetch the data for the first page.

  4. Implement a method that fetches the data for a specific page and updates the state variable. This method should be called when the user clicks a pagination button.

  5. In the render method of the data component, only display the data for the current page.

  6. Pass the pagination method and the current page as props to the pagination component.

On my pagination component, I did this, adding some tailwind styling :

const Pagination = ({ postPerPage, totalRepo, paginate}) => {

const pageNumbers =[];
  for (let i =1; i<= Math.ceil(totalRepo / postPerPage); i++){
    pageNumbers.push(i);
  }



  return (
    <div className="pagination mb-7">

    <button className="m-auto flex justify-center ">
      {pageNumbers.map(number => (
        <li key={number} className="mx-3 hover:scale-110    rounded-md border-solid    border-2 hover:bg-emerald-700 px-1 text-center ">
          <a onClick={()=> paginate (number) } href="#" className="px-4">
            {number} 
          </a>
        </li>
      ))} 
    </button>

    </div>
  )
};
export default Pagination;

Implement the proper SEO

There are several ways to implement SEO (Search Engine Optimization) in a React application:

  1. Use a library like react-helmet to manage the <head> element of the page and dynamically add meta tags and title tags.

  2. Use a library like react-snap to pre-render the page on the server and send the static HTML to the client. This can help with SEO as the search engine crawlers will see the fully rendered page.

  3. Make sure to use descriptive, relevant titles and meta tags for each page of the application.

  4. Use semantic HTML tags like <header>, <footer>, and <main> to help search engines understand the structure of the page.

  5. Use react-router to create unique URLs for each page of the application, and make sure to use descriptive URLs that include keywords.

Note: To install react-helmet, you can use the following command:

Input npm install react-helmet in the terminal box and hit enter.

Once react-helmet is installed, you can use it in your React components like this:

import { Helmet } from "react-helmet";

return (

    <>

    <Helmet>
      <title> Daniels GitHub</title>
      <meta name="descripiton" content="Daniels Github Repository"/>
      <meta name="Keywords" content="Github, Daniel, Repositories, Developer"/>
    </Helmet>
 {/* rest of the component */}
    </div>
  );
}

Implementing Error Boundry

Error boundaries are a feature of React that allows you to catch JavaScript errors anywhere in the component tree, log the error, and display a fallback UI instead of the component tree that crashed.

To create an error boundary, you need to create a new component that extends React.Component and defines a componentDidCatch lifecycle method.

Here is an example of an error boundary component:


import { ErrorBoundary } from "react-error-boundary";

const ErrorFallback = ({ error, resetErrorBoundary }) => {

  return (
    <div>
      <p>{error.message}</p>
      <button onClick={() => resetErrorBoundary} className="border-green-400 border-2 p-3 hover:bg-emerald-800" >Try Again</button>
    </div>
  );
};

To use the error boundary, you can wrap the component tree that you want to protect with the ErrorBoundary component:

<ErrorBoundary>
<MyComponent />
</ErrorBoundary>

If an error occurs in the MyComponent tree, the ErrorBoundary will catch the error and display the fallback UI.

It's important to note that error boundaries only work for errors thrown in the lifecycle methods of a component (such as componentDidMount or render) or in the constructor of a class component. Errors thrown in functions like event handlers are not caught by error boundaries.

Implementing 404 page

To create a 404 page in a React application, you can create a new component that displays a "404 - Page not found" message or any other content you want to show to the user when a page is not found.

I made use of the Notfound.js component for this.

import React from "react";
import { Link } from "react-router-dom";
import { Helmet } from "react-helmet";


function NotFound() {
    return (

      <div className="text-center">
      <Helmet>
        <title>Not NotFound</title>
        <meta name="descripiton" content="Error Page"/>
      <meta name="Keywords" content="Error"/>
    </Helmet>

        <h2 className="text-2xl ">OPS!.. YOU STUMBLED ON THE WRONG BLOCK</h2>
        <h1 className="text-8xl">404 ERROR</h1>
       <button className="px-3 py-2 hover:bg-slate-100 hover:text-slate-900">
       <Link to="./">
        Click here to go back to Base
        </Link>
        </button>
        {/* <Link to="./"></Link> */}
      </div>
    );
  }

  export default NotFound;

To display the 404 page when a page is not found, you can use the Routes component from react-router and specify a default route that renders the 404 page component:

 import NotFound from "./component /NotFound";

<Routes>
      <Route path="/" element={<Home />} />
      <Route path="/Repositories" element={<Repository />}>
      <Route path="./FirstRepo" element={<FirstRepo />}>
</Route>
 </Route>

<Route path="/Contact" element={<Contact />} />

<Route path="*" element={<NotFound />} />
 </Routes>

export default App;

The 404-page component can be customized to display any content you want, such as a message, a search form, or a link to the home page.

Pages Preview

Here is the preview of my Homepage

Repositories Page

Contact Page

Conclusion

Attempts have been made to ensure that this project is a success, but there is room for improvement and new ideas. I'm open to Ideas, contributions, recommendations, comments, etc.
I hope to get better at React.js so I can develop more interesting projects soon.

Here are reference links:
GitHub Repo: https://github.com/udofa18/github-ass

Live Link: https://github-6ec9l8tk0-udofa18.vercel.app/

Thanks