request data from Github api

1.7k Views Asked by At

I wanted to import data(get users) from https://docs.github.com/en/rest/reference/users#list-users the code in JS file(reactjs) is like

const { Octokit } = require("@octokit/rest");
const octokit = new Octokit();

async function myAsyncMethod() {
  const result = await octokit.request("GET /users");
  console.log(result.data);
}
myAsyncMethod();

but in the browser, didn't show anything, it's the correct way to get the data?

1

There are 1 best solutions below

0
On BEST ANSWER

It all depends on where do you want to call this piece of code.

For instance, let's say that you need to call it as soon as the component that you're going to display is rendered. In that case, you will need to use the useEffect hook, and call your function from there.

See the following piece of code (I'm using the component App just for the example).

import React, { useEffect } from "react";
const { Octokit } = require("@octokit/rest");

export default function App() {
  const octokit = new Octokit();

  useEffect(() => {
    getGithubUsers();
  });

  async function getGithubUsers() {
    const result = await octokit.request("GET /users");
    console.log(result.data);
  }

  return <></>;
}