dasbene
dasbene

Reputation: 31

React Native: Write value to variable outside of a inner function

i just startet with react native and currently working on a couchdb api for our project. I am doing my rest requests with fecht. But within the inner function i cannot write my responsetext (json) to variable i want to return.

_getDocument(pID)
{
    var result = "getDocument failed"

    var document = "https://"
        + this.connection.user + ":"
        + this.connection.password + "@"
        + this.connection.server + "/"
        + this.connection.database + "/"
        + pID;

    fetch(document)
        .then((response) => response.text())
        .then((responseText) => {

            result = responseText;
            Alert.alert('Fetch', result , [{text: 'ok'}])

        }).catch((error) => {
        console.warn(error);
    });

    Alert.alert('_getDocument', result , [{text: 'ok'}])

    return result;
}

at the end of my function the variable result still has the value "getDocument failed" and not my json string. i already tried to store my response text somewhere else by calling another function but that didn't work as well.

Upvotes: 3

Views: 1774

Answers (1)

Tom Walters
Tom Walters

Reputation: 15616

You need to learn about async vs sync - in your code above you're running a series of synchronous statements - both assignments of the variables result and document, then running an asynchronous statement: fetch, then running two more sync statements using Alert and return.

We call the fetch() method asynchronous because it runs in the background and won't interrupt the code execution, by using the two then() statements you're utilising JS promises in which the functions you're passing (both response.text() and the second callback), will be executed when the fetch request finishes processing. This makes sense for an API call, as it could take some time.

You just need to re-think the structure of your code, possibly using a callback within the promise resolution function:

 _getDocument(pID) {
    // Variable declarations...

    fetch(document)
        .then((response) => response.text())
        .then((responseText) => {

        result = responseText;
        Alert.alert('Fetch', result , [{text: 'ok'}])

        this.fetchCompleted(result)

    }).catch((error) => {
        console.warn(error);
    });
}

fetchCompleted (result) {
    Alert.alert('_getDocument', result , [{text: 'ok'}])
    // Do something with result
}

Or, if you're executing this within a Component, you could simply set the state instead of running the callback:

this.setState({
    data: result
})

Upvotes: 1

Related Questions