Created
August 6, 2019 04:12
-
-
Save Harshmakadia/5ff83b92cbce8ea20adbbc6946574216 to your computer and use it in GitHub Desktop.
Hooks to make API call in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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