Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧭 What You’ll Learn
By the end of this chapter, you will be able to:
🌍 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:
🔑 Step 1: Get Your
OpenWeatherMap API Key
🔧 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:
bash
npm
install react-native-dotenv
env
WEATHER_API_KEY=your_api_key_here
jsx
import
{ WEATHER_API_KEY } from '@env';
Make sure to configure Metro bundler to support
react-native-dotenv.
✅ Summary
You now know how to:
Display weather icon, temperature, humidity, and wind speed
BackAnswer:
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.
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.
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.
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.
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.
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.
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.
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.
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.
Answer:
You can add features like:
These upgrades help turn a simple app into a portfolio-level
project.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)