Reputation: 2017
Im learning react native, by building a simple weather application
In my index.ios.js I have:
const iconNames = {
Clear: 'md-sunny',
Rain: 'md-rainy',
Thunderstorm: 'md-thunderstorm',
Clouds: 'md-cloudy',
Snow: 'md-snow',
Drizzle: 'md-umbrella'
}
class App extends Component {
componentWillMount() {
//loads before component loaded
this.state = {
temp: 0,
weather: 'Clear'
}
}
componentDidMount(){
//loads after Component loads for first time
this.getLocation()
}
getLocation() {
navigator.geolocation.getCurrentPosition(
(posData) => fetchWeather(posData.coords.latitude,posData.coords.longitude)
.then(res => this.setState({
temp:res.temp,
weather:res.weather
})),
(error) => alert(error),
{timeout:10000}
)
}
render() {
return(
<View style={styles.container}>
<StatusBar hidden={true}/>
<View style={styles.header}>
<Icon name={iconNames[this.state.weather]} size={80} color={'white'}/>
<Text style={styles.temp}>{this.state.temp}°</Text>
</View>
<View style={styles.body}>
<Text>its raining</Text>
<Text style={styles.subtitle}>rain</Text>
</View>
</View>
)
}
}
Im updating the weather icon state here:
<Icon name={iconNames[this.state.weather]} size={80} color={'white'}/>
Which changes the icon as expected, but the icon seems to disappear after a second, and when I reload the app the same happens. The icon appears then disappears.
If I hard code the value like this, the icon stays there as expected:
<Icon name={'md-snow'} size={80} color={'white'}/>
Upvotes: 0
Views: 95
Reputation: 3671
Your Icon appears at the first time because you are setting a default value in your componentWillMount.
Then, after the component renders you call componentDidMount and tries to update the state on your getLocation method.
Assuming the Icon disappears after it renders, we can say the problem is in your getLocation method.
By checking the docs, it looks like you have to setup some permissions to use geolocation. Just make sure you have this allowed: https://facebook.github.io/react-native/docs/geolocation.html
Then you call a fetchWeather
method. I couldn't understand where did it came from. Check if it's working as expected.
And finally the piece where the error should be: this.setState
. Try adding a console.log to your res.weather
to check it's return. If it returns null, try adding console.log(res)
to check what you are getting.
From this you may have the following scenarios:
1) Your res.weather or res is returning null. Then I suggest to check the docs of this method you are trying to use, maybe you forgot something. Also add some console.logs to make sure if your code is returning everything as expected.
2) Your res.weather returns a value which doesn't exists an icon with the same name. In this case you should use a switch(res.weather) case
and set the state with the correctly string based on the return of your weather
Hope it helps.
Upvotes: 1