React Native
Data model
Set up the weather data model.
Weather data
A weather record has at least three fields: city (the city name), temp (temperature) and condition (sunny, cloudy, rainy). Holding these in an object makes sense.
For example, for London: {`{ city: 'London', temp: 14, condition: 'Cloudy' }`}. This object lives in the app's weather state and the screen reads from it.
You saw object state in the State group. We use the same pattern here: const [weather, setWeather] = useState({'{ city: 'London', temp: 14, condition: 'Cloudy' }'}).
Define the weather state
From the State group you remember: useState takes an initial value and returns a value-setter pair. For object state the initial value is an object.
Here we write const [weather, setWeather] = useState({'{ city: 'London', temp: 14, condition: 'Cloudy' }'}). On the first render the screen shows London; when the user picks a city, we rewrite the object with setWeather.
Later, when the city changes, we will swap the whole object: setWeather({'{ city: 'Manchester', temp: 12, condition: 'Rainy' }'}). Because a city change swaps all three fields, no spread is needed.
Exercise Add the weather state
Add a weather state to the App component with useState. The initial value should be {`{ city: 'London', temp: 14, condition: 'Cloudy' }`}. Export the App function.
Show example solution
import { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
function App() {
const [weather, setWeather] = useState({ city: 'London', temp: 14, condition: 'Cloudy' });
return (
<View style={styles.container}>
<Text>Weather</Text>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' }
});
export default App;
Test yourself
-
Match the data fields
- city
- City name
- temp
- Temperature value
- condition
- Weather condition
- weather
- State object
-
Which field holds the temperature?
Show answer
condition — temp carries the temperature as a number.
-
useState initial object
import { useState } from 'react';
function App() {
const [weather, setWeather] = ____({ city: 'London', temp: 14, condition: 'Cloudy' });
}
Show answer
import { useState } from 'react';
function App() {
const [weather, setWeather] = useState({ city: 'London', temp: 14, condition: 'Cloudy' });
}
Next lesson: Display