CPRG-306 Week 8

Fetching Data


Agenda

  1. HTTP: Methods, Status Codes
  2. JS: Promises, Async/Await, and Fetch API
  3. React: useEffect Hook
  4. Coding Demo

HTTP (Hypertext Transfer Protocol)

  • Application layer protocol for transmitting hypermedia documents
  • Used to request and send data over the internet
  • Stateless: Each request is independent of the others
  • Client-server model: Client sends requests, server sends responses

HTTP, cont'd

  • REST (Representational State Transfer) is an architectural style for designing networked applications
  • RESTful APIs use HTTP methods to perform CRUD operations
  • JSON is a common data format used in RESTful APIs

HTTP Request Methods

  • GET: Retrieve data
  • POST: Create new data
  • PUT: Update existing data
  • PATCH: Partial update
  • DELETE: Remove data

HTTP Request Example

Browser sends a GET request (https://webdev2.warsylewicz.ca/week-8) to fetch data from a server

GET /week-8 HTTP/2
Host: webdev2.warsylewicz.ca
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:131.0) Gecko/20100101 Firefox/131.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br, zstd
Referer: https://webdev2.warsylewicz.ca/week-8
...

HTTP Response

  • Server sends a response back to the client
  • Contains the requested data and metadata
  • Status code indicates the success or failure of the request
  • Headers provide additional information about the response
  • Body contains the data, e.g. HTML content, JSON data

HTTP Status Codes

  • 1xx: Informational
  • 2xx: Success
  • 3xx: Redirection
  • 4xx: Client Error
  • 5xx: Server Error

Common HTTP Status Codes

  • 200 OK: Request was successful
  • 201 Created: Resource was created
  • 204 No Content: Request was successful, no content to return
  • 400 Bad Request: Invalid request
  • 401 Unauthorized: Authentication required
  • 404 Not Found: Resource not found
  • 500 Internal Server Error: Server error

HTTP Response Example

HTTP/2 200
access-control-allow-origin: *
age: 167807
cache-control: public, max-age=0, must-revalidate
content-disposition: inline; filename="fetching-data"
content-encoding: br
content-type: text/html; charset=utf-8
...

JS Promises

  • A promise is an object that represents the eventual completion (or failure) of an asynchronous (non-blocking) operation
  • Three states: pending, fulfilled, rejected
  • Pending -> Fulfilled (.then) or Rejected (.catch)
  • Callback functions are passed to .then and .catch
  • Promises are chainable and can be used to handle multiple asynchronous operations

JS Async/Await

  • Instead of using .then and .catch, we can use async and await to handle promises
  • async keyword is used to define an asynchronous function
  • await keyword is used to "pause" the execution of the function until the promise is resolved
  • try and catch blocks can be used to handle errors
  • Much cleaner and easier to read than using .then and .catch

Notation Comparison

// Using .then and .catch
fetch("https://api.example.com/data") // Fetching data returns a promise
  .then((response) => response.json()) // When the fetch promise is resolved, prarsing the JSON returns another promise
  .then((data) => console.log(data)) // When the parsing promise is resolved, logs the data
  .catch((error) => console.error(error)); // If there is an error, logs the error
 
// Using async/await
async function fetchData() {
  try {
    const response = await fetch("https://api.example.com/data"); // Pauses here until the promise is resolved returning the response.
    const data = await response.json(); // Pauses here until the promise is resolved returning the data.
    console.log(data); // Does not pause here.
  } catch (error) {
    console.error(error);
  }
}

Fetch API

  • Provides a way to make HTTP requests and handle responses
  • Returns a promise which when resolved, returns the response to the request
  • Can be used to fetch data from an API, send data to a server, etc.
const response = await fetch("https://api.example.com/data");
const data = await response.json(); // or response.text(), etc.

React useEffect Hook

  • Used to perform side effects in functional components
  • A side effect is any code that affects something outside the scope of the component
  • Side effects include data fetching, timers, manual DOM manipulation
  • Runs after every render by default
  • Can be used to run code only when certain values change

useEffect Syntax

useEffect(() => {
  // Code to run
}, [dependencies]);
  • The function passed to useEffect is the effect
  • The second argument is an array of dependencies
  • If the dependencies change, the effect will run again
  • If the dependencies are empty, the effect will only run once
  • If the dependencies are omitted, the effect will run after every render. This is not recommended.

Coding Demo

  • Use Dog API (opens in a new tab)
  • When the page loads, display a random image of a dog
  • Display the list of breeds in a dropdown
  • When a breed is selected, display a random image of that breed