Skip to content

Instantly share code, notes, and snippets.

@Harshmakadia
Created August 6, 2019 04:10
Show Gist options
  • Select an option

  • Save Harshmakadia/6d495c1c0136dcc94a43a91279584499 to your computer and use it in GitHub Desktop.

Select an option

Save Harshmakadia/6d495c1c0136dcc94a43a91279584499 to your computer and use it in GitHub Desktop.

Revisions

  1. Harshmakadia created this gist Aug 6, 2019.
    84 changes: 84 additions & 0 deletions class_api_call.jsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,84 @@
    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);