Fabiospecial Fabiospecial - 3 days ago 6
Javascript Question

React Native - Assign this.state.var to a variable

I need to pass the string "this.state.localita" to var "loc" for fetch data from JSON.

If I print this.state.localita i can read the string, but if I assign that to the var loc it's says JSON Unhandle promise.

componentDidMount() {
AsyncStorage.getItem("localita").then((value) => {
this.setState({"localita": value});
}).done();
this._refreshData();
}

_refreshData() {
var loc = this.state.localita; // Here is the problem

fetch('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22' +
loc +'%2C%20Italy%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')

.then((response) => response.json())
.then((rjson) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(rjson.query.results.channel.item.forecast)
});
});
}
}

Answer

I think the problem is that this.state.localita doesn't have a value at the time that you expect it to. The AsyncStorage.get() method is asynchronous, but you call this._refreshData() synchronously. As such, AsyncStorage.get()probably hasn't fired its accept promise by the time that you are queryingthis.state.localita`.

What you really need to do is the following:

componentDidMount() {
    AsyncStorage.getItem("localita").then((value) => {
        this.setState(
            {"localita": value},
            this._refreshData.bind(this)
        );
    });
}

_refreshData() {
    var loc = this.state.localita; // Here is the problem

    if (! loc) {
        return
    }

    // fetch, etc...
}

This only calls setState once the AsyncStorage has the value you need, and then queues up a call to refreshData only after the state has been updated. We use .bind(this) here to ensure that the method knows about this correctly, as passing a function reference as a callback loses the this context.

Comments