Data model
- React Native course
- Beginner
- Lesson 84/116
- 6 min
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.
Practice 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.
Starter code
import { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
function App() {
// define the weather state here
return (
<View style={styles.container}>
<Text>Weather</Text>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' }
});
export default App;Sample 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;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the data fields
| Term | Meaning |
|---|---|
city |
City name |
temp |
Temperature value |
condition |
Weather condition |
weather |
State object |
2 Which field holds the temperature?
- temp
- city
- condition Correct answer
- weather
Explanation: temp carries the temperature as a number.
3 useState initial object
import { useState } from 'react';
function App() {
const [weather, setWeather] = ____({ city: 'London', temp: 14, condition: 'Cloudy' });
}
import { useState } from 'react';
function App() {
const [weather, setWeather] = useState({ city: 'London', temp: 14, condition: 'Cloudy' });
}
Explanation: useState is called with an object as the initial value.