Share

learning api by creating weather wall: a simple forecast app using react and open weather map ⛅️

forecast app using react

In this blog post, we are going to make a 5-day forecast app using React and an API. For this first part, we will focus on fetching the api from open weather map. Let’s use Manila, but it’s up to you which city you want to use. Also we will display the temperature in Celsius format.  

Parts 📝

  1. Fetching the data
  2. Adding a search field – by city name
  3. Finishing design

Tools we’ll use 🔧

Getting started 📢

  1. Register to openweathermap.org. You will then receive an email to verify your account.
  2. After that, go to the directory where you want to save your project, there right click and choose your terminal.
  3. To start, run this command in your terminal
npx create-react-app <project-name>

In my case, I used weather-wall. After that wait for a decade, kidding. It might take some minutes, but it will load for sure. You just have to be patience. Tounge stick out emoji

note: you can only use lowercases letters when running create-react-app

  1. Of course, after that, change your directory to the one you just created.

cd weather-wall
  1. Then, type and hit
npm start

~ this command will open a new tab with title, ‘React App’, now that’s it! You’ve created your first react app. Cute emoji here This will also allow you to see the changes you’re making 

because it updates live in your local host server.  

  1. Now, open your project in your text editor (personally I use VSCode) 
  2. Create a file in the src folder and save it as js file. I name my file, Week.js.
  3. Then go to App.js, modify the file and remove the part of the code we will not need. Make sure to import the js file you created. 

import Week from './Week';

Make it look like the code below.

import React, { Component } from 'react';
import './App.css';
import Week from './Week';
 
class App extends Component {
  render() {
    return (
      <div className="App">
        <Week />
      </div>
    );
  }
}
 
export default App;

To check if things work the way it should, write anything in the Week.js file and see if the changes is shown.

For now, here’s the Week.js file:

import React from 'react';
 
class Week extends React.Component {
    render() {
        return(
            <div>
                <h1>test</h1>
            </div>
        )
    }
}
 
export default Week;

Don’t forget the last line, which is the:


<strong>export default Week;</strong>

because it will cause an error. 

Getting the data from open weather 📈

Now, we are going to fetch the date from the API. I used open weather in this project, but you can freely use other API’s, there’s so much available out there.   

Since, what we did first was to register, what we’ll do now is get our API KEY from openweathermap.org. Go to My API Keys, and there you can copy your key. Or you can also get your key from the email you received from open weather. Either way, the next thing we would do is encrypt our key so we can use it.

9. In your terminal, type and enter the command


touch .env

📌 note: you should be in your project root directory

After creating your .env file, set your API Key there. For instance,

WEATHER_API_KEY=<your_key>

Add the .env  file to gitignore. 

To use the key, declare it in your Week.js file

const API_KEY = process.env.REACT_APP_WEATHER_API_KEY;

Now we are going to create a method called componentDidMount in our Week.js file, inside it we will now fetch the API from open weather map. To fetch:

api.openweathermap.org/data/2.5/forecast?q=<city_name>,<state_code>&units=<unit_type>&appid=<your_key>

In this case, I will use Manila from Philippines, and Celsius as our unit. Metric is for Celsius while imperial if you want to display your forecast in Fahrenheit.


const weatherURL = `http://api.openweathermap.org/data/2.5/forecast?q=Manila,PH&units=metric&APPID=${API_KEY}`

📌 note: make sure to use this ` ` instead of ‘  ‘ because it won’t work.  You can try and see for yourself the difference. 

Read this to get familiar with parts of a URL.

Checking if the API works using Postman 📎

10. Open your Postman app, and type the URL for fetching with a get request. In Postman, you will see that there are a lot of types of requests. Here’s to understand some: get means retrieval, post obviously you are adding, put means update and etc. You can read more about different methods here. (link for source)

If you get a 200 as a response, it means you have successfully fetched the data, and you will now see the data in a json format. But if you get a 401 response, it means you are not authorized to access the data, there might be wrong in your APPID or API key. Double check your key, make sure that you changed the value to your actual key instead of the variable name only. After modifying your URL, try sending the request again.

Some status codes and their meanings:

  • 200 means ok
  • 404 means not found
  • 500 means server error
  • 401 means unauthorized

Take note that 404 is an error on the browser side, while 500 is an internal server error. To read more, go here.

After making sure your API works, let’s procced to  filtering the data we got.  Add the following code below. 

 fetch(weatherURL)
    .then(res => res.json()) 
    .then(data => {
      const dailyData = data.list.filter(reading => reading.dt_txt.includes("18:00:00"))
      this.setState({
        fullData: data.list,
        dailyData: dailyData
      }, () => console.log(this.state))
    })
  }

//explaining parts of fetch

.then(res => res.json())

Add this below code too!

state = {
    fullData: [],
    dayData: []
  }

11. Create a new js file for formatting days, I named mine Day.js. Add the code below:

import React from 'react';
var moment = require('moment');
 
const Day = ({ reading }) => {
    let newDate = new Date();
    const weekday = reading.dt * 1000
    newDate.setTime(weekday)
  
 
  
    return (
      <div className="col-sm-2 col-md-2">
        <div className="card">
          <h3 className="card-title">{moment(newDate).format('dddd')}</h3>
          <p className="text-muted">{moment(newDate).format('MMMM Do, h:mm a')}</p>
 
          <img className="weather-condition"    src={`http://openweathermap.org/img/wn/${icon}@2x.png`} />    
          <h2>{Math.round(reading.main.temp)} °C</h2>
          <div className="card-body">
 
            <p className="card-text">{reading.weather[0].description}</p>
          </div>
        </div>
      </div>
    )
  }
  
  export default Day;

12.  Make sure to install moment.js using this command in your terminal.


<strong>npm install moment --save</strong>

13. Now to, format the forecast, add this code:

formatDays = () => {
    return this.state.dayData.map((reading, index) => <Day reading={reading} key={index} />)
  }

14. To display, we are going to use bootstrap, install it too!

 //command to install bootstrap 

Let’s add a container for our headings.

<div className="container">
       <h2 className="display-2">5-Day Forecast</h2>
       <h4 className="display-4">Manila, PH</h4>
 <div className="row justify-content-center">

And finally, to show the data we fetched: 


 {this.formatDays()}

That’s it! You should now see the 5-day forecast in Manila in Celsius format. In the next part, we will add a search field according to the city. That way we are not only limited to knowing Manila’s forecast. 

Adding design ✒️

It’s up to you now how you will design your weather app! Or we can do it together in the next post. Take note that we’re going to add other features too some other time.

I used photoshop to layout this logo concept and to edit the background that I have used. You can just download stock photos or use gradient for you background or anything creative.

Here’s what it looked like after I added some design. You can share yours too, you know.

 learning api by creating weather wall

Github Repo: Weather Wall

learn more 📑…

📍 as developer students, why do we need to learn git? (and use github)

📍 understanding the difference between git and github 

📍 affordable coding training centers for students and beginners in the Philippines