KeykoYume KeykoYume - 3 months ago 8
Javascript Question

React Native Changing Variable with State

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!

Answer

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.

Comments