await is only valid in async function - if else function - react-native

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 => {

Related

localVarFormParams.getHeaders is not function when using openai.createImageEdit()

this is my function
const generatedDalleImage = async () => {
await openai.createImageEdit(
selectedImage,
selectedMaskImage,
"human face",
1,
"1024x1024"
).then((response) => {
console.log(response);
setGeneratedImage(response.data.data[0].url)
}).catch(err => {
console.log(err);
});
}
i am getting this error
localVarFormParams.getHeaders is not function when using openai.createImageEdit()
i am really stuck in this one so any help is appreciated

Variables not registering in await function

What I'm trying to accomplish here is use req.body to pass the query arguments and when it hits the endpoint, the variables should be used in the create function of the Notion API. Unfortunately, the variables are registering as undefined. I figure that it's a scope issue, but I can't figure out how to structure this.
export default async function handler(req, res) {
const {
companyName,
email,
panelNames,
tags,
markers,
inquiry
} = req.body;
try {
await notion.pages
.create({
// use variables here
companyName: companyName //says undefined
}).then((result) => {
res.
})
} catch (e) {
console.log(e);
}
}
//Frontend code
const bodyQuery = {
companyName: "Example",
email: "example#gmail.com",
...
};
try {
await fetch("/api/v1/submit", headers)
.then((res) => {
return res.json();
})
.then((res) => {
setTests(res);
});
} catch (e) {
console.log("e:", e);
}
Because you did not pass bodyRequest to the request, so your backend can not receive data. Here's an example how to do it:
await fetch('/api/v1/submit', {
method: 'POST',
headers,
body: JSON.stringify(bodyRequest)
})
.then((res) => {
return res.json();
})
.then((res) => {
setTests(res);
});
And make sure your REST endpoint is POST. Hope it help!

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

Store the result of an async function into a variable

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)

Express Middleware Setting Header Error

I'm trying to implementation a fairly simple middleware function to my Express application that just adds a useCache value to the request object being passed to the main handler but for some reason, I'm getting a Can't set headers after they were sent error.
const cacheControl = (req, res, next) => {
if (lastPulled === null) lastPulled = Date().getDay()
req.useCache = Date().getDay() === lastPulled
next()
}
app.use(cacheControl)
app.get('/missions', (req, res) => {
if (req.useCache) res.status(200).json({ result: cache })
fetch(dumpUrl)
.then(data => data.text())
.then(result => {
cache = result
res.status(200).json({ result })
})
.catch(e => res.status(500).json({ result: e.message }))
})
I've read that most of the time if the error is produced by the middleware it is due to multiple next() calls, but that doesn't apply here, unless I'm missing something obvious.
When I remove the cacheControl middleware from the application, there is no longer an error, but I can't figure out what in the function is causing the error! Any pointers are helpful!
I'm guessing it's because res.json() is firing twice:
app.get('/missions', (req, res) => {
if (req.useCache) res.status(200).json({ result: cache })
fetch(dumpUrl)
.then(data => data.text())
.then(result => {
cache = result
res.status(200).json({ result })
})
.catch(e => res.status(500).json({ result: e.message }))
})
// if res.useCase is true, set headers and reply
if (req.useCache) res.status(200).json({ result: cache })
// then fetch and reply again (which generates the error)
fetch(dumpUrl)
.then(data => data.text())
.then(result => {
cache = result
res.status(200).json({ result })
Change it to this to utilize explicit return
app.get('/missions', (req, res) => {
if (req.useCache) return res.status(200).json({ result: cache })
return fetch(dumpUrl)
.then(data => data.text())
.then(result => {
cache = result
res.status(200).json({ result })
})
.catch(e => res.status(500).json({ result: e.message }))
})
The nature of the error is similar to when you do this:
problem
function problem() {
if (true === true) console.log('send problem')
console.log('send garbage by accident')
}
console.log(problem())
solution
function solution() {
if (true === true) return console.log('send solution')
return console.log('send nothing')
}
console.log(solution())
return is how you exit a function. Your issue is that your code was checking the if condition, but then continuing past it because it wasn't told to stop once it found that condition.
The old way or less terse way to write your function would be like:
app.get('/missions', (req, res) => {
if (req.useCache) {
res.status(200).json({ result: cache })
} else {
fetch(dumpUrl)
.then(data => data.text())
.then(result => {
cache = result
res.status(200).json({ result })
})
.catch(e => res.status(500).json({ result: e.message }))
}
})
Without the else in there, it executes every if statement it comes across until it reaches the end of the function, unless you use the return keyword as the cue to exit right there.
Keep in mind, using return inside a .then() function will resolve the promise, it won't exit from the upper scope if there are more .then()s chained on.