Reputation: 1
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
Upvotes: 0
Views: 1058
Reputation: 1204
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)})
);
}
Upvotes: 0
Reputation: 3262
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.
Upvotes: 1
Reputation: 1
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))
}
Upvotes: 0