Created
August 6, 2019 04:10
-
-
Save Harshmakadia/6d495c1c0136dcc94a43a91279584499 to your computer and use it in GitHub Desktop.
Class Component in React for making API calls
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 from "react"; | |
import ReactDOM from "react-dom"; | |
import "./styles.css"; | |
class GithubCommit extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
commitHistory: [], | |
page: 1, | |
isLoading: true | |
}; | |
this.loadMoreCommit = this.loadMoreCommit.bind(this); | |
} | |
componentDidMount() { | |
this.loadCommitHistory(); | |
} | |
loadMoreCommit() { | |
const { page } = this.state; | |
this.setState( | |
{ | |
page: page + 1 | |
}, | |
() => this.loadCommitHistory() | |
); | |
} | |
loadCommitHistory() { | |
const { page } = this.state; | |
// Fetching data from FaceBook Jest Repo | |
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 => | |
this.setState({ commitHistory: response.items, isLoading: false }) | |
) | |
.catch(error => console.log(error)); | |
} | |
render() { | |
const { commitHistory, isLoading } = this.state; | |
return ( | |
<div> | |
<h1> API calls with React Class Component </h1> | |
{isLoading && <p>Wait I'm Loading comments for you</p>} | |
{commitHistory.length !== 0 && ( | |
<button onClick={() => this.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