Build a Stunning Weather App with React Native: A Step-by-Step Beginner’s Guide

460 0 0 0 0

📘 Chapter 3: Connecting to the Weather API

🧭 What You’ll Learn

By the end of this chapter, you will be able to:

  • Understand how APIs work in the context of a mobile app
  • Get and configure your OpenWeatherMap API key
  • Make GET requests using fetch or axios
  • Handle loading states and errors
  • Parse and display weather data
  • Structure your code to separate logic and UI

🌍 What Is an API and How Do We Use It?

An API (Application Programming Interface) lets your app talk to external services—like OpenWeatherMap, which provides real-time weather data.

In our weather app, we’ll make a GET request to OpenWeatherMap, send a city name, and receive a JSON object with:

  • Temperature
  • Weather condition
  • Humidity
  • Wind speed
  • Weather icon reference

🔑 Step 1: Get Your OpenWeatherMap API Key

  1. Go to https://openweathermap.org/
  2. Sign up and verify your email
  3. Navigate to the API keys section in your account
  4. Copy your default key (you’ll use it in your app)

🔧 Step 2: Install Axios (optional)

You can use the built-in fetch() or install axios for cleaner code.

bash

 

npm install axios


🔗 Step 3: Build the API Call

Here’s a sample API endpoint (replace with your key):

bash

 

https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY&units=metric

🔹 Breakdown:

Parameter

Meaning

q

City name

appid

Your API key

units=metric

Celsius temperature format


📄 Sample Function Using Axios

jsx

 

import axios from 'axios';

 

const API_KEY = 'YOUR_API_KEY_HERE';

 

export const getWeatherByCity = async (city) => {

  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`;

 

  try {

    const response = await axios.get(url);

    return {

      temp: response.data.main.temp,

      description: response.data.weather[0].description,

      humidity: response.data.main.humidity,

      wind: response.data.wind.speed,

      icon: response.data.weather[0].icon,

    };

  } catch (error) {

    throw error;

  }

};


🧩 Integrate API into Your React Native App

📄 In App.js

jsx

 

import React, { useState } from 'react';

import {

  View, Text, TextInput, Image, StyleSheet, TouchableOpacity

} from 'react-native';

import { getWeatherByCity } from './api/weatherService';

 

export default function App() {

  const [city, setCity] = useState('');

  const [weather, setWeather] = useState(null);

  const [loading, setLoading] = useState(false);

  const [error, setError] = useState('');

 

  const fetchWeather = async () => {

    setLoading(true);

    setError('');

    try {

      const data = await getWeatherByCity(city);

      setWeather(data);

    } catch (e) {

      setError('City not found or API error.');

    } finally {

      setLoading(false);

    }

  };

 

  return (

    <View style={styles.container}>

      <Text style={styles.title}>️ WeatherNow</Text>

 

      <TextInput

        style={styles.input}

        placeholder="Enter city name"

        value={city}

        onChangeText={setCity}

      />

 

      <TouchableOpacity onPress={fetchWeather} style={styles.button}>

        <Text style={styles.buttonText}>Get Weather</Text>

      </TouchableOpacity>

 

      {loading && <Text style={styles.loading}>Loading...</Text>}

      {error ? <Text style={styles.error}>{error}</Text> : null}

 

      {weather && (

        <View style={styles.resultBox}>

          <Text style={styles.temp}>{weather.temp}°C</Text>

          <Image

            style={styles.icon}

            source={{

              uri: `http://openweathermap.org/img/wn/${weather.icon}@2x.png`,

            }}

          />

          <Text style={styles.description}>{weather.description}</Text>

          <Text>Humidity: {weather.humidity}%</Text>

          <Text>Wind: {weather.wind} km/h</Text>

        </View>

      )}

    </View>

  );

}


🎨 Sample Styles

jsx

 

const styles = StyleSheet.create({

  container: {

    padding: 20,

    marginTop: 50,

  },

  title: {

    fontSize: 28,

    textAlign: 'center',

    marginBottom: 20,

  },

  input: {

    borderWidth: 1,

    padding: 10,

    borderRadius: 8,

    marginBottom: 10,

  },

  button: {

    backgroundColor: '#0a84ff',

    padding: 12,

    borderRadius: 8,

    alignItems: 'center',

    marginBottom: 20,

  },

  buttonText: {

    color: '#fff',

    fontWeight: 'bold',

  },

  loading: {

    textAlign: 'center',

    marginVertical: 10,

  },

  error: {

    color: 'red',

    textAlign: 'center',

  },

  resultBox: {

    alignItems: 'center',

    marginTop: 20,

  },

  temp: {

    fontSize: 48,

    fontWeight: 'bold',

  },

  icon: {

    width: 100,

    height: 100,

  },

  description: {

    fontSize: 20,

    fontStyle: 'italic',

    marginBottom: 10,

  },

});


🔁 Optional: Using fetch() Instead of Axios

jsx

 

const getWeatherByCity = async (city) => {

  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`;

 

  const response = await fetch(url);

  if (!response.ok) {

    throw new Error('Error fetching weather');

  }

 

  const data = await response.json();

  return {

    temp: data.main.temp,

    description: data.weather[0].description,

    humidity: data.main.humidity,

    wind: data.wind.speed,

    icon: data.weather[0].icon,

  };

};


📊 Table: API Response Fields You’ll Use

Field

Description

main.temp

Temperature in °C

weather[0].description

Weather condition (text)

main.humidity

Humidity percentage

wind.speed

Wind speed in km/h

weather[0].icon

Icon code for weather image


🔐 Handling API Errors and Edge Cases

Common Issues

Problem

Solution

Invalid API key

Verify in OpenWeatherMap dashboard

City not found

Show user-friendly error message

API limit reached

Upgrade to premium / reduce frequency

No internet connection

Catch and handle error in UI


🔒 Securing API Keys in React Native (Bonus Tip)

You can use dotenv to avoid hardcoding the API key:

  1. Install:

bash

 

npm install react-native-dotenv

  1. Create .env file:

env

 

WEATHER_API_KEY=your_api_key_here

  1. Use it:

jsx

 

import { WEATHER_API_KEY } from '@env';

Make sure to configure Metro bundler to support react-native-dotenv.


Summary

You now know how to:

  • Sign up and use OpenWeatherMap
  • Fetch and display real-time weather data in React Native
  • Use axios or fetch() for API calls
  • Handle user input, loading, and errors

Display weather icon, temperature, humidity, and wind speed

Back

FAQs


❓1. Do I need to know React to build a React Native weather app?

Answer:
While React Native shares many concepts with React (like components, props, and state), you don’t need to be an expert in React to start. Basic knowledge of JavaScript and understanding of components will help you get going quickly.

❓2. What’s the difference between Expo and React Native CLI?

Answer:
Expo is a framework and platform that simplifies React Native development. It’s great for beginners.
React Native CLI provides full native access and is preferred for advanced, production-grade apps. For this weather app, Expo is usually enough.

❓3. Which weather API should I use?

Answer:
You can use any public weather API, but OpenWeatherMap is beginner-friendly, well-documented, and offers a free tier with real-time weather data, making it ideal for this project.

❓4. Is this weather app cross-platform?

Answer:
Yes! React Native apps work on both Android and iOS. You’ll be building one codebase that runs on both platforms with native-like performance.

❓5. Can I use geolocation to show weather for the current location?

Answer:
Absolutely. React Native supports location access through packages like expo-location or react-native-geolocation-service, which lets you fetch the user’s coordinates and use them in your API requests.

❓6. Do I need to pay for an API key?

Answer:
No. Most APIs like OpenWeatherMap offer a free tier that includes current weather data, which is enough for this app. Just sign up and grab your API key from their dashboard.

❓7. How do I manage the app’s state?

Answer:
This app uses React Hooks—mainly useState for managing input and weather data, and useEffect for API calls. For more advanced apps, you might consider using context or libraries like Redux.

❓8. How do I style the UI in React Native?

Answer:
React Native uses the StyleSheet.create() method to define CSS-like styles. You can also use Flexbox for layout and third-party libraries like react-native-elements or styled-components for more flexibility.

❓9. Can I deploy this app to the Google Play Store or Apple App Store?

Answer:
Yes, with additional steps. You’ll need to create a developer account for each store, build release versions, test thoroughly, and follow each platform’s publishing guidelines. Expo also offers services like EAS Build to simplify deployment.

❓10. What else can I add to make the app more advanced?

Answer:
You can add features like:

  • 7-day weather forecasts
  • Hourly breakdowns
  • Save favorite cities
  • Background images based on weather
  • Dark mode support
  • Weather animations (e.g., rain, sun, snow)


These upgrades help turn a simple app into a portfolio-level project.