Skip to content

Instantly share code, notes, and snippets.

@Harshmakadia
Created August 6, 2019 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Harshmakadia/5ff83b92cbce8ea20adbbc6946574216 to your computer and use it in GitHub Desktop.
Save Harshmakadia/5ff83b92cbce8ea20adbbc6946574216 to your computer and use it in GitHub Desktop.
Hooks to make API call in React
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function GithubCommit() {
const [page, setPage] = useState(1);
const [commitHistory, setCommitHistory] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const loadMoreCommit = () => {
setPage(page + 1);
};
useEffect(() => {
fetch(
`https://api.github.com/search/commits?q=repo:facebook/react+css&page=${page}`,
{
method: "GET",
headers: new Headers({
Accept: "application/vnd.github.cloak-preview"
})
}
)
.then(res => res.json())
.then(response => {
setCommitHistory(response.items);
setIsLoading(false);
})
.catch(error => console.log(error));
}, [page]);
return (
<div>
<h1> API calls with React Hooks </h1>
{isLoading && <p>Wait I'm Loading comments for you</p>}
{commitHistory.length !== 0 && (
<button onClick={loadMoreCommit}>Load More Commits</button>
)}
{commitHistory.map((c, index) => (
<div key={index}>
{c.commit && (
<>
<div>
<h2 style={{ textDecoration: "Underline" }}>
{c.commit.committer.name}
</h2>
<p>{c.commit.message}</p>
</div>
<hr />
</>
)}
</div>
))}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<GithubCommit />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment