Practice and reinforce the concepts from Lesson 7
Practice API integration by building a simple weather display component that fetches data and handles errors gracefully.
import React, { useState } from 'react';
import { View, Text, Button, TextInput } from 'react-native';
const WeatherApp = () => {
const [city, setCity] = useState('');
const [weather, setWeather] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const fetchWeather = async () => {
// TODO: Implement API call
console.log('Fetching weather for:', city);
};
return (
<View style={{padding: 20}}>
<Text style={{fontSize: 24, marginBottom: 20}}>Weather App</Text>
<TextInput
value={city}
onChangeText={setCity}
placeholder="Enter city name..."
style={{borderWidth: 1, padding: 10, marginBottom: 10}}
/>
<Button
title={loading ? "Loading..." : "Get Weather"}
onPress={fetchWeather}
disabled={loading || !city.trim()}
/>
{error && (
<Text style={{color: 'red', marginTop: 10}}>{error}</Text>
)}
{weather && (
<View style={{marginTop: 20, padding: 15, backgroundColor: '#f0f0f0'}}>
<Text style={{fontSize: 18}}>Weather in {weather.name}</Text>
{/* TODO: Display weather data */}
</View>
)}
</View>
);
};
export default WeatherApp;
Get a free API key from OpenWeatherMap:
https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric
const fetchWeather = async () => {
if (!city.trim()) return;
setLoading(true);
setError('');
try {
// TODO: Make API call
// TODO: Parse response
// TODO: Update weather state
} catch (err) {
// TODO: Handle errors
} finally {
setLoading(false);
}
};
Show these fields from the API response:
Handle these error cases:
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`
);
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const data = await response.json();
setWeather(data);
catch (err) {
if (err.message.includes('404')) {
setError('City not found. Please check spelling.');
} else if (err.message.includes('401')) {
setError('Invalid API key.');
} else {
setError('Unable to fetch weather. Please try again.');
}
}
Your app should:
Complete this activity and submit your work through the Activity Submission Form