📕
SEIRFX
  • Introduction
  • About These Notes
  • Schedule
  • Unit 2
    • Node
      • Internet Fundamentals
      • Full-Stack Fundamentals
      • Intro to Node
      • Node Modules
      • Node Packages
    • Express
      • Intro to Express
      • Routes
      • Routes Lab
      • Views
      • Templates
      • Layouts & Controllers
    • CRUD & REST
      • GET & POST
      • GET & POST Lab
      • PUT & DELETE
    • API Calls in Express
      • Axios
      • Request (no longer maintained)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
  • Development Workflow
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
      • Objects Lesson
      • Objects quick guide
      • Object-ception
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Scope
      • Callbacks
      • Higher Order Functions
      • Callbacks Review Lab
      • Timing Functions
      • Iterators
      • Combining Data Types
      • Combining Data Types Lab
    • Javascript in the browser
      • DOM and Events
      • DOM Manipulation
      • DOM Review
      • DOM Review Lab
      • HP DOM Lab
      • Programmatic DOM Manipulation
      • Grids & Pyramids
      • DOM & Data
      • DOM Events
      • Color Palette Picker
      • Sketchpad
    • HTML5 Canvas
    • How To Reduce Redundancy
    • OOP
      • Westworld Lab
      • OOP Factories
      • OOP Inheritance
      • OOP Inheritance Lab
      • Tomagotchi Lab
      • OOP Space Battle
      • OOP Snowman
      • (2019) JavaScript OOP
      • (2016) OOP with Classes
      • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Left over Node/Express
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Being Successful in SEI
    • Internet Fundamentals
      • Internet Lab
    • Adjacent Workflow
      • UX/UI
      • Wireframing Exercise: Build an Idea
      • Agile
    • Post SEI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Learning Objectives
  • Introducing fetch()
  • Codealong - Kanye West Quotes
  • Fetching Kanye in a React Component
  • Let's use axios instead!

Was this helpful?

  1. React (Updated 2019)
  2. Fetch and APIs

APIs with Fetch and Axios

PreviousFetch and APIsNextFetch the Weather

Last updated 4 years ago

Was this helpful?

Learning Objectives

After this lesson, you will be able to:

  • Identify the pieces of a fetch() call

  • Create a React component that calls an API

Introducing fetch()

So... we know what an API is. Now what?

How can we use an API to dynamically manipulate the DOM with the given data? We can use fetch().

In the past, these have been called AJAX requests. As you'll come to learn, fetch() allows us to build single page applications that do not require refreshes.

AJAX, which stands for "Asynchronous Javascript and XML," is the method through which we are able to make HTTP requests. The standard requests we will be making are GET POST PUT PATCH and DELETE.

Type of Request

What's It Do?

GET

Read ('give me movie names from your database')

POST

Create ('here's a new movie for your database')

PATCH

Update ('hey, this movie has a new title'))

PUT

Update ('hey, this movie totally changed')

DELETE

Delete ('that movie is so bad you should just take it out of the database')

The browser packages this together using fetch() and sends it off to a server. The server then listens to your request and provides a response. It looks something like this:

Request/Response

When you browse to your favorite websites, your browser is making a request and the server is providing a response. fetch() allows us to perform the same type of requests over a network. Imagine fetching weather information and rendering it on your website. You can use fetch() to build these applications.

Taking a look at fetch in action

That was a lot! Let's take a look at fetch() in action.

Imagine we want to fetch() the number of astronauts currently aboard the International Space Station (ISS). Good thing there is an API for that, right? This API allows us get the information using the following URL:

http://api.open-notify.org/astros.json

The API provides a response that looks like the following:

{
    "number": 5,
    "people": [
        {"craft": "ISS", "name": "Oleg Novitskiy"},
        {"craft": "ISS", "name": "Thomas Pesquet"},
        {"craft": "ISS", "name": "Peggy Whitson"},
        {"craft": "ISS", "name": "Fyodor Yurchikhin"},
        {"craft": "ISS", "name": "Jack Fischer"}
        ],
        "message": "success"
}

If you'd like, you can copy and paste the API URL into a browser to see this happen.

This particular API tells us the number of people currently in space on the ISS and their names. It also happily gives us "message: success" so we know it worked!

We can fetch this JSON easily using Javascript.

How? The skeleton code looks like this:

fetch(url)
  .then(function(response) {
    // Here you get the data to modify or display as you please
    })
  })
  .catch(function(ex) {
    // If there is any error, you will catch it here
  })

Or, in ES6 syntax:

fetch(url)
  .then((response) => {
    // Here you get the data to modify or display as you please
    })
  })
  .catch((ex) => {
    // If there is any error, you will catch it here
  })

Let's look at what we would apply this for our astronauts:

let issApi = 'http://api.open-notify.org/astros.json';
fetch(issApi)
  .then((response) => {
    return response.json()
  }).then((json) => {
    console.log('JSON from the ISS', json)
  }).catch((ex) => {
    console.log('An error occured while parsing!', ex)
  })

Let's break this API call down into a few steps.

  • let issApi = 'http://api.open-notify.org/astros.json': First, we define our API URL to fetch from

  • fetch(issApi): We call fetch on that API URL.

  • .then((response) => { return response.json(): We take the response when the server provides it. We return the response.json()

  • .then((json) => { console.log('JSON from the ISS', json): We take that json and console.log it.

  • catch((ex): If an error occurs, we catch it and log it.

That's as simple as fetch is. While there are other ways to handle the response (such as html or blob), this approach makes writing requests to APIs and other network calls in Javascript easy.

Codealong - Kanye West Quotes

Q: Which React.Component method should API calls be made from?

Q: What does it mean to make GET request?

We are asking the server to send us data to read. To GET means to "read."

Fetching Kanye in a React Component

Let's go back to your blog project (so make sure it's running!).

You can use fetch() API directly inside of a React Component to render a quote. We'll be using the Home component, so open Home.js to edit.

  • Start by changing the Home component to have an empty componentDidMount() method.

  • Set the stage for returning a quote in the div by changing the text to be an <h1> with the text "My favorite Kanyw quote:"

Let's use axios instead!

import React, {Component} from 'react';

class Home extends Component {

  componentDidMount() {
      /* nothing here... yet! */
  }

  render() {
    return (
      <div>
        <h1>My favorite Kanye quote:</h1>
      </div>
    )
  }
}


export default Home

or with a functional component...

import React, {useEffect} from 'react'

const Home = () => {
   useEffect() {
      /* nothing here... yet! */
   }

   return (
      <div>
        <h1>My favorite Kanye quote:</h1>
      </div>
   )
  }

We can now tell our component to fetch a Kanye quote and then set it to our state. We do this by adding the axios.get() call inside of componentDidMount().

Calling this.setState() then triggers a re-render inside of our component.

You should have this:

import React, {Component} from 'react';
import axios from 'axios';

class Home extends Component {

  state = {
    kanye: ''
  }

  componentDidMount() {
    let kanyeRest = 'https://api.kanye.rest/';
    // fetch a poem
    axios.get(kanyeRest).then( response => {
      // set state
      this.setState{kanye: response.data.quote}
    }).catch(err => console.log(err))
  }

  render() {
    let quote = this.state.kanye;
    return (
      <div>
        <h1>My favorite Kanye quote:</h1>
        {quote}
      </div>
     )
  }
}

or as a functional component...

import React, {useState, useEffect} from 'react'
import axios from 'axios'

const Home = () => {
   let [kanye, setKanye] = useState('')

   useEffect(() => {
   let kanyeRest = 'https://api.kanye.rest/'
   axios.get(kanyeRest)
   .then( response => {
        setKanye(response.data.quote)
      })
   .catch(err => console.log(err.message))
   }, [])
   return (
        <div>{kanye}</div>
   )
}

Let's test it out!

  • Add an if statement under render.

    • This simply checks to be sure that axios.get() has completed before render() tries to return the movie - otherwise it returns "Loading...".

    • For this especially, it's important that the state is declared in the constructor. This way, the if statement does not fail if the asynchronous setState() hasn't completed the update yet.

render() {
       let quote = this.state.kanye;
     if (this.state.kanye){
       return (
         <div>
           <h1>My favorite Kanye quote:</h1>
           {quote}
         </div>
       )
     }
     return (
       <div>
         <h1>My favorite Kanye quote:</h1>
         Loading...
       </div>
     )
  }

and one more time, as a functional component:

if(kanye){
   return (
   <div>
      <h1>My favorite Kanye quote:</h1>
      <div>{kanye}</div>
      <p>Lo, my heart doth swoon... Such a way with words.</p>
   </div>
   )
}
return (
   <div>
      <h1>My favorite Kanye quote:</h1>
      <div>Loading...</div>
   </div>
)

You're done! Your home page should load a random Kanye quote!

For more information than you probably ever wanted to know about fetching data in React, these articles by Robin Weiruch make for a pretty complete resource:

    • 🏴‍☠️ BEWARE! There be HOOKS here! 🏴‍☠️

Production Warning! It is important to note that while this is an ES6 standard, do not support it; yet Edge does. You may need a polyfill for live projects. If you need a polyfill for a production project, .

It is time for you to build a very simple component that shows a randomly generated Kanye West Quote. We'll do this using the . Before doing so, challenge yourself to a mini quiz.

componentDidMount(). Per the , If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

The official tells developers that any network requests should be placed inside of the componentDidMount method.

fetch is great and all... but let's take this opportunity to test out another common library! axios is Promise based HTTP client for the browser and node.js! More detailed information can be found in their .

some browsers such as Internet Explorer
Github's polyfill is very popular
Kanye Rest
React documentation
React documentation
README on github
How to Fetch Data in React
Fetching Data with React Hooks