Rocket Academy Bootcamp
  • 🚀Welcome to Bootcamp!
  • 🛠️Logistics
    • Course Schedules
    • Course Methodology
    • Required Software
    • LinkedIn Education Badge
  • 📚General Reference
    • Naming, Casing, and Commenting Conventions
    • VS Code Tips
    • Recommended Resources
  • 🪨0: Foundations
    • 0.1: Command Line
    • 0.2: Git
      • 0.2.1: Branches
    • 0.3: GitHub
      • 0.3.1: Pull Requests
    • 0.4: JavaScript
      • 0.4.1: ES6
      • 0.4.2: Common Syntax
      • 0.4.3: Reference vs Value
      • 0.4.4: Classes
      • 0.4.5: Destructuring and Spread Operator
      • 0.4.6: Promises
        • 0.4.6.1: Async Await
    • 0.5: Node.js
      • 0.5.1: Node Modules
      • 0.5.2: NPM
      • 0.5.3: Nodemon
  • 🖼️1: Frontend
    • 1.1: HTML
    • 1.2: CSS
      • 1.2.1: Layout
    • 1.3: React
      • Styling in ReactJs
      • Using Styling Libraries with React
      • React Deployment
    • 1.E: Exercises
      • 1.E.1: Recipe Site
      • 1.E.2: Portfolio Page
      • 1.E.3: World Clock
      • 1.E.4: High Card
      • 1.E.5: Guess The Word
    • 1.P: Frontend App
  • 🏭2: Full Stack
    • 2.1: Internet 101
      • 2.1.1: Chrome DevTools Network Panel
      • 2.1.2: HTTP Requests and Responses
    • 2.2: Advanced React
      • 2.2.1: AJAX
      • 2.2.2: React Router
      • 2.2.3: useContext
      • 2.2.4: useReducer
      • 2.2.5: Environmental Variables
      • 2.2.6: React useMemo - useCallback
    • 2.3: Firebase
      • 2.3.1: Firebase Realtime Database
      • 2.3.2: Firebase Storage
      • 2.3.3: Firebase Authentication
      • 2.3.4: Firebase Hosting
      • 2.3.5: Firebase Techniques
    • 2.E: Exercises
      • 2.E.1: Weather App
      • 2.E.2: Instagram Chat
      • 2.E.3: Instagram Posts
      • 2.E.4: Instagram Auth
      • 2.E.5: Instagram Routes
    • 2.P: Full-Stack App (Firebase)
  • 🤖3: Backend
    • 3.1: Express.js
      • 3.1.1 : MVC
    • 3.2: SQL
      • 3.2.1: SQL 1-M Relationships
      • 3.2.2: SQL M-M Relationships
      • 3.2.3: SQL Schema Design
      • 3.2.4: Advanced SQL Concepts
      • 3.2.5: SQL - Express
      • 3.2.6: DBeaver
    • 3.3: Sequelize
      • 3.3.1: Sequelize One-To-Many (1-M) Relationships
      • 3.3.2: Sequelize Many-To-Many (M-M) Relationships
      • 3.3.3: Advanced Sequelize Concepts
      • 3.3.4 Database Design
    • 3.4: Authentication
      • 3.4.1: JWT App
    • 3.5: Application Deployment
    • 3.E: Exercises
      • 3.E.1: Bigfoot JSON
      • 3.E.2: Bigfoot SQL
      • 3.E.3: Bigfoot SQL 1-M
      • 3.E.4: Bigfoot SQL M-M
      • 3.E.5: Carousell Schema Design
      • 3.E.6: Carousell Auth
    • 3.P: Full-Stack App (Express)
  • 🏞️4: Capstone
    • 4.1: Testing
      • 4.1.1: Frontend React Testing
      • 4.1.2: Backend Expressjs Testing
    • 4.2: Continuous Integration
      • 4.2.1 Continuous Deployment (Fly.io)
      • 4.2.2: Circle Ci
    • 4.3: TypeScript
    • 4.4: Security
    • 4.5: ChatGPT for SWE
    • 4.6: Soft Skills for SWE
    • 4.P: Capstone
  • 🧮Algorithms
    • A.1: Data Structures
      • A.1.1: Arrays
        • A.1.1.1: Binary Search
        • A.1.1.2: Sliding Windows
      • A.1.2: Hash Tables
      • A.1.3: Stacks
      • A.1.4: Queues
      • A.1.5: Linked Lists
      • A.1.6: Trees
      • A.1.7: Graphs
      • A.1.8: Heaps
    • A.2: Complexity Analysis
    • A.3: Object-Oriented Programming
    • A.4: Recursion
    • A.5: Dynamic Programming
    • A.6: Bit Manipulation
    • A.7: Python
  • 💼Interview Prep
    • IP.1: Job Application Strategy
    • IP.2: Resume
    • IP.3: Portfolio
Powered by GitBook
On this page
  • Learning Objectives
  • Introduction
  • Setup
  • Base: Show current weather for user-provided city
  • Instructions
  • Example: console.log response to understand response format
  • Example: Chain multiple Axios requests without nesting
  • Comfortable: Show hourly and daily forecasts for coming days
  • More Comfortable: Show forecast data in a graph
  • Submission
  • Reference Solution
  1. 2: Full Stack
  2. 2.E: Exercises

2.E.1: Weather App

Previous2.E: ExercisesNext2.E.2: Instagram Chat

Last updated 1 year ago

Learning Objectives

  1. Know how to send an HTTP request and handle response data in a frontend app

  2. Know how to send an AJAX request and load response data in a React app

  3. Know how to chain promises with multiple AJAX calls

  4. Know how to read API documentation to use a new API

Introduction

We will build a weather app that shows the latest weather forecast for a city that a user enters.

Setup

  1. Fork and clone the

  2. to access Open Weather's free weather API. After confirming your email you will receive an API key to use to make API requests. This can take up to 24 hours so please do this during pre-class.

Base: Show current weather for user-provided city

Instructions

  1. Create an input field where users can input the city they would like to check the weather for. Provide instructions on the page so users know to enter a city name in the input.

  2. When a user inputs a city name, use to retrieve the weather in that city and display it to the user. The app should update the weather when the user inputs a new city or submits the same city again.

    1. To install to make requests, run npm i axios and import Axios from the relevant component.

    2. We will send GET requests because we are retrieving and not creating or updating any data.

    3. Notice the API URL uses to customise the API call. We specify query parameters in key-value pairs separated by =, where we separate each key-value pair with &.

    4. When developing with APIs, feel free to console.log API responses to understand the format of the response before writing code logic. See below code example for an illustration.

    5. We will need to use to translate location names to coordinates before querying the current weather data API. You may find it helpful to chain promises with .then syntax.

      1. To chain multiple asynchronous function calls with .then, we can return the promises of the subsequent function calls in their .then callbacks instead of creating a nested .then. See example below for illustration.

    6. We may find it helpful to specify metric units for the units parameter of the API. This will return all temperature values in Celsius instead of Kelvin.

    7. Consider displaying the relevant icon next to the weather. Open Weather returns an icon code with weather info and we can retrieve the relevant icon using and an HTML img tag.

Making our API key public

By making API requests to Open Weather directly from our frontend app, we are effectively making our Open Weather API public because all frontend code is visible to users. This is discouraged in production apps because hackers can use our Open Weather account to make requests for free. We will learn how to build backend servers to hide sensitive data such as API keys in Module 3.

Example: console.log response to understand response format

We can console.log the response to the API request to understand its format before we try to parse data from the response.

App.jsx
handleSubmit = (event) => {
  event.preventDefault();
  axios
    .get(
      `https://api.openweathermap.org/geo/1.0/direct?q=${cityInputValue}&limit=1&appid=${OPEN_WEATHER_API_KEY}`
    )
    .then((response) => {
      console.log(response);
      // Write remaining logic once we understand response format
    });
};

The logging revealed that the data I want is in response.data[0].

Example: Chain multiple Axios requests without nesting

Promise syntax is flexible, and there are preferred and less-preferred ways of handling promises. Rocket prefers we only have 1 level of nesting for chained promises for readability.

Bad

We should never need more than 1 level of nesting for .thens. This makes our code harder to read, because the .then execution flow becomes non-linear.

App.jsx
handleSubmit = (event) => {
  event.preventDefault();
  axios
    .get(
      `https://api.openweathermap.org/geo/1.0/direct?q=${cityInputValue}&limit=1&appid=${OPEN_WEATHER_API_KEY}`
    )
    // City geo data is in response.data[0]
    // Arrow functions with no curly braces return value after arrow
    .then((response) => response.data[0])
    .then((cityGeoData) =>
      axios
        .get(
          `https://api.openweathermap.org/data/2.5/weather?lat=${cityGeoData.lat}&lon=${cityGeoData.lon}&appid=${OPEN_WEATHER_API_KEY}&units=metric`
        )
        .then((response) => {
          const { data: weatherData } = response;
          console.log(weatherData);
        })
    );
};

Good

We can return the promise returned by the 2nd axios.get in its .then callback, and obtain the result of that promise in the subsequent .then. This allows us to have only 1 level of nesting.

App.jsx
handleSubmit = (event) => {
  event.preventDefault();
  axios
    .get(
      `https://api.openweathermap.org/geo/1.0/direct?q=${cityInputValue}&limit=1&appid=${OPEN_WEATHER_API_KEY}`
    )
    // City geo data is in response.data[0]
    // Arrow functions with no curly braces return value after arrow
    .then((response) => response.data[0])
    .then((cityGeoData) =>
      axios.get(
        `https://api.openweathermap.org/data/2.5/weather?lat=${cityGeoData.lat}&lon=${cityGeoData.lon}&appid=${OPEN_WEATHER_API_KEY}&units=metric`
      )
    )
    .then((response) => {
      const { data: weatherData } = response;
      console.log(weatherData);
    });
};

Comfortable: Show hourly and daily forecasts for coming days

More Comfortable: Show forecast data in a graph

Submission

Submit a pull request to the main branch of Rocket's Weather App repo and share your PR link in your section Slack channel.

Use HTTPS URLs for API requests for deployment

HTTPS sites can only make HTTPS requests and not HTTP requests. To deploy our app to GitHub Pages, update all API URLs in our app to use HTTPS instead of HTTP (i.e. https://myurl.com instead of http://myurl.com. Open Weather Geocoding and Weather Icons docs share HTTP links, but luckily they both also support HTTPS.

Reference Solution

.then callbacks accept both values and promises as return values. If a previous .then callback returns a promise, the subsequent .then callback will receive that promise's resolved value as a parameter. Read more on .then behaviour in .

In addition to the current weather, display a daily forecast, represented by hourly data to the user in tables. You may find the helpful.

Render the forecast data in a graph instead of a table. You may find React chart libraries like helpful.

If you would like to deploy your app to the internet, follow Vitejs GitHub Pages .

Here is and a for this exercise. You can do better!

🏭
Rocket Academy Weather App Repo
Create an Open Weather account
Open Weather's current weather data API
Axios
URL query parameters
Open Weather's geocoding API
Open Weather's Icon URLs
official docs
Open Weather API documentation
Recharts
deployment instructions here
reference code
reference deployment
console.log can help us reveal the format of an API response. Source: Rocket Academy