简体   繁体   中英

Fetch react native get data out of the function

I'm trying to make a fetch function that return the data like a classic function. like this :

function fetchGetData(idUser){
        fetch('url?idU='+idUser)
        .then((response)=>console.log(response))
        .then((responseText)=>{
            if(responseText.result!='true'){
                console.log(responseText)
             return parseInt(responseText) // return the data (a number for me)
            }
            else {
              return 0 ; 
            }
        });
    }

then I want to use the function like this : var data = fetchGetData(id); I'm new on react, I don't know if its possible. In my context, i can't use states to save it in the function. Any ideas? Thank you

Because you want to asgin response of the request to a vaiable like a sync function response ( var data = fetchGetData(id); ), It's better to use async/await for this case. It's your rewritten fetchGetData:

async function fetchGetData(idUser){
  try {
    let response = await fetch('url?idU='+idUser);
    console.log(response);
    let responseText = await response; // are you sure it's not response.json();?
    if(responseText.result!='true'){
      console.log(responseText);
      return parseInt(responseText) // return the data (a number for me)
    } else {
      return 0 ; 
    }
  } catch(error) {
    console.error(error);
  }
}

Now you can assign it's returned value by calling the function:

var data = await fetchGetData(id);

In this way, you are using async actions link sync actions.

If expected response is JSON , chain .json() to response to return javascript object, else use .text() to return response as plain text

function fetchGetData(idUser) {
  return fetch('url?idU=' + idUser) // note `return` fetch from function call
    .then(response => {
      return response.text() // if `response` is `JSON` use `.json()` here
    })
    .then(responseText => {
    //  if (responseText.result != 'true') { // is expected response `JSON` or text?
        console.log(responseText);
        return parseInt(responseText) // return the data (a number for me)
    //  } else {
    //    return 0;
    //  }
    })
    .catch(err => Promise.reject(err))
}

I had a similar problem.. use _bodyText properties

function fetchGetData(idUser){
        fetch('url?idU='+idUser)
        .then((response)=>{console.log(response._bodyText)
              return parseInt(response._bodyText)})
        );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM