Store the result of an async function into a variable - react-native

I am trying to store the result of an async function into a variable,but the output of my code didn't seems to be the expected one. What am I doing wrong ?
async function get_happy_songs() {
let urlOfS = 'http://10.0.2.2:5000/happy_songs'
try {
let response = await fetch(
urlOfS, {
method: 'GET'
}
);
let json = await response.json();
//console.log(json.melodies);
return json.melodies;
} catch (error) {
console.error(error);
}
}
//var happy_songs = [];
let happy_songs = get_happy_songs();
console.log(happy_songs)

Try like this.
async function get_happy_songs() {
let urlOfS = 'http://10.0.2.2:5000/happy_songs'
return fetch(urlOfS, {
method: 'GET'
}).then((response) => response.json())
.then((responseJson) => {
console.log('response object:', responseJson)
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
let happy_songs = await get_happy_songs();
console.log(happy_songs)

Related

react native make accessToken global

im using rn-secure-storage to save authState when using oauth2, then i have class AppHelper to control all network function like below:
import RNSecureStorage, { ACCESSIBLE } from 'rn-secure-storage'
export const accessToken = async() => {
await RNSecureStorage.get("authState").then((value) => {
console.log("authState", value);
return JSON.parse(value).accessToken
}).catch((err) => {
console.log("can not get authState", err);
});
};
export const getData = (url, tag = 'getData') => {
return fetch(url, {
method : 'GET',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization' : 'Bearer ' + accessToken
}
})
.then((response) => {
console.log(tag, 'Bearer ' + accessToken);
return response.text();
})
.then((json) => {
console.log(tag, json)
return json;
})
.catch((error) => {
handleError(err)
console.log(tag, error, url)
});
}
export const handleError = (error) => {
if (error.response.code == 401){
alert('Unauthorized')
}else{
console.log('network call failed', error)
}
}
im coding native before, so im not familiar with React native syntax. I just want to get access token to apply in network call, but my code show error:
_getMasterInfoApi Bearer function _callee() {
return _regenerator.default.async(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return _regenerator.default.awrap(_rnSecureStorage.default.get("authState").then(function (value) {
console.log("authState", value);
return JSON.parse(value).accessToken;
}).catch(function (err) {
handleError(err);
}));
case 2:
case "end":
return _context.stop();
}
}
}, null, null, null, Promise);
}
Can anyone help? thanks in advance

React-native-fetch-blob GET request error

I am replacing axios to rn-fetch-blob in my react-native project. In the request I ping my server with credentials and I expect a response.
The old request with axios is as follows and works perfectly:
export const postWorkspace =
(newWorkspace: Workspace): AppThunk =>
async (dispatch) => {
console.log('addWorkspace Start');
dispatch(setIsLoading(true));
let configOption = {
headers: {
'Access-Control-Allow-Origin': '*',
'X-AUTH-USER': newWorkspace.credentials.email,
'X-AUTH-TOKEN': newWorkspace.credentials.password,
},
};
await axios
.get(`${newWorkspace.url}/api/ping`, configOption)
.then(async (resp) => {
console.log('addWorkspace resp', resp);
try {
await storeWorkspaceToStorage(newWorkspace);
} catch (e) {
console.error(e);
}
})
.catch((err) => {
console.log('addWorkspace err', JSON.stringify(err));
return Promise.reject(err);
})
.finally(() => dispatch(setIsLoading(false)));
};
This is how I transformed the code with rn-fetch-blob:
export const postWorkspace=
(newWorkspace: Workspace): AppThunk =>
async (dispatch) => {
console.log('addWorkspace Start');
dispatch(setIsLoading(true));
let configOption = {
'Access-Control-Allow-Origin': '*',
'X-AUTH-USER': newWorkspace.credentials.email,
'X-AUTH-TOKEN': newWorkspace.credentials.password,
};
await RNFetchBlob
.fetch('GET', '${newWorkspace.url}/api/ping', configOption)
.then( async(resp) => {
console.log('addWorkspace resp', resp);
try {
await storeWorkspaceToStorage(newWorkspace);
} catch (e) {
console.error(e);
}
})
.catch((err) => {
//console.log(err.info().status);
console.log('addWorkspace err', JSON.stringify(err));
return Promise.reject(err);
})
.finally(() => dispatch(setIsLoading(false)));
};
The new request with rn-fetch-blob returns this error:
response error "line":126349,"column":34,"sourceURL":"http://localhost:8081/index.bundle?platform=android&dev=true&minify=false"
When I opend the file "http://localhost:8081/index.bundle?platform=android&dev=true&minify=false" around line 1262349 the code looks like this, I can't understand what went wrong:
var req = RNFetchBlob[nativeMethodName];
req(options, taskId, method, url, headers || {}, body, function (err, rawType, data) {
subscription.remove();
subscriptionUpload.remove();
stateEvent.remove();
partEvent.remove();
delete promise['progress'];
delete promise['uploadProgress'];
delete promise['stateChange'];
delete promise['part'];
delete promise['cancel'];
promise.cancel = function () {};
//line 126349
if (err) reject(new Error(err, respInfo));else {
if (options.path || options.fileCache || options.addAndroidDownloads || options.key || options.auto && respInfo.respType === 'blob') {
if (options.session) session(options.session).add(data);
}
respInfo.rnfbEncode = rawType;
resolve(new FetchBlobResponse(taskId, respInfo, data));
}
});
});
I am doing this since rn-fetch-blob is basically one of the few libraries that allows react-native to ping a server with no SSL certification.
Thank you

Fetching Data as a Json format in react native return error when mapping data

The error returned is : undefined is not an object (evaluating 'json.map') ,knowing that my api has multiple data.
The code i use to fetch data is :
CheckifReadLater = async () => {
const username = await AsyncStorage.getItem('username');
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn');
if (isLoggedIn == 1 && username) {
await fetch(Config.backendAPI+`/readlater.php?username=${username}&select`)
.then((response) => {
reactotron.log("Response : ",response);
response.json();
})
.then((json) => {
json.map((product, index) => {
if (product.id == this.props.product.id) {
this.setState({
isReadLater: true,
})
}
});
})
.catch((error) => reactotron.log('This is the error: ',error))
}
reactotron.log("Readlater : ",this.state.isReadLater);
}
How can i solve this problem ?
You should return the response.json(); on the first .then function for it to be available on the next .then.
Do this:
await fetch(Config.backendAPI+`/readlater.php?username=${username}&select`)
.then((response) => {
reactotron.log("Response : ",response);
// update your code here
return response.json();
})

await is only valid in async function - if else function

I check if there is such data in the firestore with (if (docSnapshot.exists)). I need to call await function when it goes inside else, but in this way I get an error "await is only valid in async function". How can I use the await function inside if else?
drawRoad = async (userLatitude,userLongitude,BranchLocationLatitude,BranchLocationLongitude,minPrice,shippingPrice) => {
try {
let userid = (this.props.UserStore.UserId).toString()
await firestore().collection('Tracking').doc(userid).onSnapshot(docSnapshot => {
if (docSnapshot.exists){
...
}
else {
...
let rsp=await fetch(url)
rsp=await rsp.json() }
}, err => {
console.log(`Encountered error: ${err}`);
});
} catch (error) {
console.log(error)
console.log("hata_componentDidMount HomeMap")
}
}
Try something like this:
else {
...
await fetch(url)
.then(res => res.json())
.then(res => do what you want with the response like setState, console.log it or whatever)
.catch(err => console.log(err))
}
Maybe try to tell the function to be async like this.
async function drawRoad(){
await fetch(url)
.then(res => res.json())
.then(res => {

Sqlite3 returning empty array with GET request in Express

I am trying to make a get request to an sqlite3 table, using Express, based on input from a form. The fetch request works and so does the db.all, but I receive a response as an empty array from rows. I tried req.query and req.params already. Not sure where the error is.
//server.js
app.get('/names/state', (req, res, next) => {
const stateValue = req.query.state;
db.all(`SELECT name FROM states WHERE name=$stateVal`,
{
$stateVal: stateValue
},
(err, rows) => {
res.send({rows:rows});
})
});
//script.js
const fetchOneBtn = (e) => {
e.preventDefault();
const stateVal = stateInputValue.value;
fetch(`/names/state?state=${stateVal}`)
.then(response =>{
if(response.ok){
return response.json();
}
}).then(names => {
console.log(names);
})
};
You can change your code in your backend with this code below:
app.get('/names/state', (req, res, next) => {
const stateValue = req.query.state;
var query = "SELECT name FROM states WHERE name = " + stateValue;
db.all(query, (err, rows) => {
if(err) {
console.log(err);
res.status(500).send(err);
}else {
res.send({rows});
}
})
});
Now, for your frontend, you can change with the code below:
const fetchOneBtn = async (e) => {
e.preventDefault();
const stateVal = stateInputValue.value;
try {
const response = await fetch(`/names/state?state=${stateVal}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
});
console.log(await response.json());
return await response.json();
} catch(ex) {
console.log(ex);
}
};
I hope it can help you.