Command Shift

GetImages - Walkthrough

Start by installing the axios package:

npm i axios@0.27.2

Note: We are intentionally installing version 0.27.2, as this won't conflict with Jest, which we will use when writing tests.

We need this to make our GET request.

Inside your requests folder, create a file called getImages.js.

That file contents should look like this:

import axios from "axios";
 
const getImages = (query) => {
  if (!query) {
    return Promise.resolve([]);
  } else {
    return axios
      .get(`https://images-api.nasa.gov/search?q=${query}`)
      .then((response) => {
        console.log(response)
      })
      .catch((err) => {
        console.log(err);
      });
  }
};
 
export default getImages;

And finally, after we’ve updated our Search.js file with our handleSubmit it should look like this:

import React, { useState } from "react";
import "../styles/search.css";
import getImages from "../requests/getImages";
 
const Search = () => {
  const [value, setValue] = useState();
 
  const handleSubmit = (event) => {
    event.preventDefault();
    getImages(value);
  };
 
  return (
    <div className="search">
      <form className="search-form" onSubmit={handleSubmit}>
        <input
          className="search-input"
          type="text"
          onChange={(e) => setValue(e.target.value)}
        />
        <button className="search-btn" type="submit">
          Go!
        </button>
      </form>
    </div>
  );
};
 
export default Search;

On this page

No Headings