0

I'm new to react and I just started playing around with state and props. What I have been trying is to fetch some data and then populate with it some card views.
This is how my code looks so far:

class Two extends React.Component {
constructor(props) { 
    super(props);
    this.state = { 
      day: "Monday",
    };
  }

// Getting monthly schedule
    getSchedules = () => {
        fetch("http://xxxxxx/getschedules.php", {method: "GET"})
        .then((response) => response.json())
        .then((responseData) => {
            AlertIOS.alert(
                "GET Response",
                "Search Query -> " + responseData.result.length)
                this.setState({day: responseData.result[1].day}); //changing state but nothing changes
        })
        .then((data) => { 
         console.log(data);
        })
        .catch(function(err) {
         console.log(err);
        })
        .done();
    }

  render() {  
            <TouchableOpacity onPress={this.getSchedules}>
              <View style={styles.card}>
              <Text>{this.state.day}</Text>
              </View>
              </TouchableOpacity>
             }
}

If I click on the card the text value is supposed to change but nothing happens. Also is there a way to change the state automatically when the page loads without having to click on the card? Any help would be greatly appreciated!

KeykoYume
  • 2,497
  • 6
  • 24
  • 48

2 Answers2

2

In your onPress code: <TouchableOpacity onPress={this.getSchedules}>

It should be <TouchableOpacity onPress={this.getSchedules.bind(this)}>

By only passing function reference this context isn't passed to getSchedules.

while1
  • 3,320
  • 19
  • 12
0

Have you checked that the fetch is working?

I tried your code with a Facebook example url and I got

Network Request Failed

in the console (CMD + D - Debug)

Followed the directions in this SO answer to add the domain to an exception list in info.plist and it worked :)

the info.plist file is in Xcode and you can update it easier by right clicking and choose "Open as > Source Code" - that way you can copy and paste the code from the above SO answer

Community
  • 1
  • 1
David
  • 7,395
  • 5
  • 29
  • 45
  • yes, I have done that and yes, it is fetching my data correctly (I have printed it in the console to check if it works and everything's fine) – KeykoYume Aug 13 '16 at 12:09