React Native - fetch(url) always returning a Promise

Asked

Viewed 537 times

1

I’m starting in React Native, I had no problems until I started making HTTP requests. I’m using this function:

async getJSON(url, parameters){
    try{
        //check if URL isn't empty
        if(url.length == 0)
            return false;

        //construct HTTP parameters
        var params = '';
        for (var key in parameters) {
            if(params.length)
                params += "&";

            params += key + "=" + encodeURIComponent(parameters[key]);
        }
        //doing request
        const response = await fetch(`${url}${params}`);
        let body = await response.json();

        return body;
    }catch(err){
        console.error(err);
        return false;
    }
}

So I got Promisse next:

Promise {_40: 1, _65: 0, _55: null, _72: Handler}
v
_40:1
_55:{success: false, msg: "segredo não informado"}
_65:1
_72:null
__proto__:Object

This JSON on the _55 object is what I want to get, I could just access and pick it up, but that would not be correct (goes that the number changes, haha).

So I adapted the code below from of that post, and entered the code before the Return body; of the first code.

Promise.resolve(body).then(function(value) {
    console.log(value); //aqui deu log do JSON!
    body = value; // essa atribuição não funcionou, por algum motivo
});

The above assignment should pass JSON to body, but in the end returned the Promise again... I tried to put a await before Promise.resolve but nothing has changed.

I looked at the documentation, sought more details and even ready-made answer templates here at Stackoverflow that use the fetch->then->then scheme. I don’t know what else to do.

  • Who knows using "state" to record the value... I will test.

1 answer

0


Since Promise.resolve is asynchronous, within a function also asynchronous, I solved the problem by placing it in the main class. It works like this:

In the main class, I call the method that returns the JSON from a webservice:

let result = conn.getJSON(this, url.login, params);

Note: The getJSON method remains the same as the first question code.

The Object Promise will be in result, then just below it I make the JSON treatment.

if(result){
     Promise.resolve(result).then(function(json) {
       //login successfully
       if(json.success){
         console.warn("loging in...");
       }else{
         console.warn("wrong login");
       }

     });
   }else{
     Alert.alert(
       'Erro LOG-2',
       'Nenhuma informação retornada do servidor. Talvez uma instabilidade na rede tenha causado isso. Tente novamente.',
            [
         {text: 'OK, vou verificar.', onPress: () => console.log('OK Pressed')},
            ],
       { cancelable: true }
      )
   }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.