Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Github API Calls with personal access token Usage with Fetch with node JS and React JS

Today, I was playing around with GitHub API and I ran into the 60 calls per hour roadblock as described here - https://developer.github.com/v3/rate_limit/

For command line testing the solution is to use PAT - https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token

I am new learner but the GitHub doc was a little confusing so I had run around a lot. Github recommends the following CURL usage

curl -u GitHubUserName:personalaccesstoken https://api.github.com/users/GitHubUserName

but, then, using it in a fetch request is a challenge for there are a number of depreciation in the pipeline on how to use things.

So, the question, how best to get this working in a simple fetch call in node JS and React JS?

like image 550
Jay Avatar asked Oct 29 '25 01:10

Jay


1 Answers

Eventually, I ended up with the following code block that gets it working.

import React, { useState, useEffect } from "react";
    
function GitHubUser({ login }) {
    const [data, setData] = useState();
    const [error, setError] = useState();
    const [loading, setLoading] = useState(false);
   
    useEffect(() => {
      if (!login) return;
      setLoading(true);
      fetch(`https://api.github.com/users/GitHubUserName`,{
        method: "GET",
        headers: {
          Authorization: `token personalaccesstoken ` 
        }
      })
        .then(data => data.json())
        .then(setData)
        .then(() => setLoading(false))
        .catch(setError);
    }, [login]);
    
    if (loading) return <h1>loading...</h1>;
    if (error)
      return <pre>{JSON.stringify(error, null, 2)}</pre>;
    if (!data) return null;
  
    return (
      <div className="githubUser">
        <img
          src={data.avatar_url}
          alt={data.login}
          style={{ width: 200 }}
        />
        <div>
          <h1>{data.login}</h1>
          {data.name && <p>{data.name}</p>}
          {data.location && <p>{data.location}</p>}
        </div>
      </div>
    );
  }
    
export default function App() {
  return <GitHubUser login="GitHubUserName" />;
}

The main confusion was that in some parts of GitHub documentation it keeps saying we should use username, and basic and what not. Perhaps it was only confusion for me, but this solves it.

like image 101
Jay Avatar answered Oct 31 '25 21:10

Jay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!