Searching API data in react

Searching API data in react

In this article, we will be implementing how to search data from from an API, this is part two of the tutorial series about react and APIs. In this tutorial we will be using Axios to make HTTP calls and the GitHub API to pull data. I will assume you have your react up and running at this point, if not, you can check out the official React documentation on how to get started.

  constructor(props) {
    super(props);
    this.state = {
      repositories: [],
      isLoading: true,
      errors: null,

      keyword: "",

      newItem: "",
      list: [],
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

once that's done, before we get to pull data from, create an input form field to capture a value we will pass to the api.

detect the changes and set the state

  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }

Lets create an input field that will capture the value we want to check for in the api data.

   <div
            style={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <input
              className="form-control"
              placeholder="Enter Name"
              type="text"
              name="keyword"
              value={this.state.keyword}
              onChange={this.handleChange}
              onBlur={this.handleChange}
              style={{
                border: "2px solid #000",
                width: "30%",
                borderRadius: "12px",
                height: "40px",
                padding: "0px 0px 0px 10px ",
                backgroundColor: "none",
                margin: "0px 2px 0px 0px ",
                fontSize: 14,
              }}
            />
          </div>

   <div
            style={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <Button
              style={{
                color: "white",
                variant: "contained",
                size: "small",
                backgroundColor: "#000",
                margin: "0px 1px 0px 0px ",
                fontSize: 28,
                height: "40px",
                fontWeight: "",
                textTransform: "none",
                textAlign: "center",
                border: "1px solid #000",
                borderRadius: "100px 100px 100px 100px",
                padding: "5px 3px ",
                width: "15%",
                boxShadow: "0px 3px 3px #E2E2E2",
                "&:hover": {
                  backgroundColor: "#000",
                },
              }}
              onClick={() => this.handleSubmit()}
            >
              Search
            </Button>
          </div>

Once that's done, we will pass the captured value to the handlesubmit method, then setState to the response coming from the API, take note 0f the async/await we are using for promises. Console the response you are getting before proceeding.


  async handleSubmit() {
    try {
      const response = await axios.get(
        `https://api.github.com/search/repositories?q=${this.state.keyword}/`
      );

console.log("check response data",response.data)
      this.setState({
        repositories: response.data.items,

        isLoading: false,
      });


      return response;
    } catch (error) {
      console.log(error.stack);
      this.setState({
        errors: error.response,
      });
    }
  }

For the last part, since we have are sending a value to the API and getting a response, lets display the data we are getting to the render method.

  {repositories.map((repo, i) => (
              <div key={repo.id}>
                <div>
                  <span >
                    {repo.full_name}
                  </span>
                </div>

                <div >
                    Default Branch:
                    <br />
                    <span>{repo.default_branch}</span>
                  </h6>

                  <h6>
                    Decription:
                    <br />
                    <span>{repo.description}</span>
                  </h6>                      
                </div>
              </div>
            ))}

That's it, you should be able to see the open source repositories with the keyword you typed in. if your are too lazy to read through the article, here is the full code with some styling

import React, { Component } from "react";

import { Button } from "react-bootstrap";
import axios from "axios";


import MainWrapper from "./mainwrapper";

export class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      repositories: [],
      isLoading: true,
      errors: null,

      keyword: "",

      newItem: "",
      list: [],
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }



  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }

  async handleSubmit() {
    try {
      const response = await axiosInstance.get(
        `https://api.github.com/search/repositories?q=${this.state.keyword}/`
      );

      this.setState({
        repositories: response.data.items,

        isLoading: false,
      });

      this.handleModalShowHide();

      return response;
    } catch (error) {
      console.log(error.stack);
      this.setState({
        errors: error.response,
      });
    }
  }

  render() {
    const { isLoading, repositories, from, to } = this.state;
    // const repodata = JSON.parse(Cookies.get("repo"));
    return (
      <React.Fragment>
        <SimpleStorage parent={this} />
        <MainWrapper className="explore-body">
          <br />
          <br />
          <br />
          <div
            style={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <input
              className="form-control"
              placeholder="Enter Name"
              type="text"
              name="keyword"
              value={this.state.keyword}
              onChange={this.handleChange}
              onBlur={this.handleChange}
              style={{
                border: "2px solid #32c709",
                width: "30%",
                borderRadius: "12px",
                height: "40px",
                padding: "0px 0px 0px 10px ",
                backgroundColor: "none",
                margin: "0px 2px 0px 0px ",
                fontSize: 14,
              }}
            />
          </div>
          <div
            style={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <Button
              style={{
                color: "white",
                variant: "contained",
                size: "small",
                backgroundColor: "#29BD00",
                margin: "0px 1px 0px 0px ",
                fontSize: 28,
                height: "40px",
                fontWeight: "",
                textTransform: "none",
                textAlign: "center",
                border: "1px solid #29BD00",
                borderRadius: "100px 100px 100px 100px",
                padding: "5px 3px ",
                width: "15%",
                boxShadow: "0px 3px 3px #E2E2E2",
                "&:hover": {
                  backgroundColor: "#29BD00",
                },
              }}
              onClick={() => this.handleSubmit()}
            >
              Search
            </Button>
          </div>
          <br />
          <br />

          <div
            className="explore-card-columns  container-fluid"
            style={{ marginBottom: "100px" }}
          >
            {repositories.map((repo, i) => (
              <div
                className="card"
                key={repo.id}
                style={{ background: "#8080801f" }}
              >
                <div className="explore-user-detail">
                  <span
                    style={{
                      color: "#32c709",
                      fontWeight: "bolder",
                      fontSize: "15px",
                    }}
                  >
                    {repo.full_name}
                  </span>
                </div>

                <div className={"card-body"}>
                  <h6>
                    Default Branch:
                    <br />
                    <span>{repo.default_branch}</span>
                  </h6>

                  <h6>
                    Decription:
                    <br />
                    <span>{repo.description}</span>
                  </h6>



                </div>
              </div>
            ))}
          </div>
        </MainWrapper>
      </React.Fragment>
    );
  }
}

export default Home;