user8684708
user8684708

Reputation:

React Native - state is not saved in object

Im trying out React Native an now im fetching a weather forecast from openweather API. the data is getting fetched after the user type in the city an click the button.

The problem is that i am trying to save the response to the state objects property "forecast" but its not beeing saved.

What am i doing wrong?

 import React, {Component} from 'react';
    import {StyleSheet, Text ,TextInput, View, Button} from 'react-native';

export default class App extends Component { 

    constructor(props){
      super(props);
      this.state = {
        text:"",
        forecast:null,
        hasData: false
      }
    }

    userTextChange = (input) => {
      this.setState({
        text:input
      })
    }

    getMovies = () => {
      var url = 'https://api.openweathermap.org/data/2.5/weather?q='+this.state.text+'&units=metric&appid=7d6b48897fecf4839e128d90c0fa1288';
      fetch(url)  
      .then((response) => response.json())
      .then((response) => {
          this.setState = ({
            forecast:response,
            hasData:true
          })
          console.log(response) <-- This is a json reponse with one object
      })
      .catch((error) => {
          console.log("Error: ",error);
      });
    }

  render() {
    return (
      <View style={styles.container} >

          <TextInput 
            style={{width:'80%',borderRadius:8,marginTop:70,height:60,backgroundColor:'#f1f1f1',textAlign:'center',borderWidth:1,borderColor:'#ccc'}}
            placeholder=""
            onChangeText={this.userTextChange}
          />

          <Button
            title="Get forecats"
            style={{backgroundColor:'#000',height:50,width:'50%',marginTop:30,marginBottom:30}}
            onPress={()=>this.getMovies()}
          />

         <View style={{width:'90%',height:'68%', backgroundColor:'rgba(0,0,0,0.5)',alignItems:'center',paddingTop:20}}>
          <Text style={{color:'#000',fontSize:22}}>{this.state.forecast.name}</Text> <-- THIS IS NULL
        </View>

         </View>

    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    alignItems:'center'
  },
});

Herer is the JSON response frpm openweather API

Upvotes: 1

Views: 686

Answers (1)

Joshua Obritsch
Joshua Obritsch

Reputation: 1293

The following line:

this.setState = ({
  forecast:response,
  hasData:true
})

should be:

this.setState({
  forecast:response,
  hasData:true
})

You should also consider initializing forecast in state to an empty object.

Upvotes: 1

Related Questions