React native async function returns empty object - javascript

I am trying to get a token stored in securestore, and pass it to url. When I try to call the api the value of the token is just an empty object. I am able to see the value t here if I alert in readToken function. Its not passed to getMovies function.
const readToken = async () => {
try {
const storedToken = await SecureStore.getItemAsync('token');
return storedToken;
} catch (e) {
console.log(e);
}
};
const getMovies = async () => {
try {
let url = 'https://someurl.de/api/getschichten/?userid=9&token='+readToken();
alert(url);
const response = await fetch(url);
const json = await response.json();
setData(json);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}

So, I changed my code according to kipnodels. Here's my code that works
let myToken = await readToken();
let url = 'https://esm.nvii-dev.de/api/getschichten/?userid=9&token='+myToken;

Related

I want to use axios's return to global state ,but Promise { <pending> }

const Board = () => {
...
const {selected} = useSelector(state => state.board);
// In Redux reducer ->
// const initialState = {
// selected : {}
// }
const getOnePost = async (id) => {
try {
const response = await axios.get(`/api/v1/post/${id}`);
const getOnePostData = await response.data;
selected = getOnePostData //I want to use Redux to use global state...
console.log(selected) //TypeError... and How to use global state..?
} catch(error) {
alert(error.response.data.message);
return Promise.reject(error)
}
}
const postClickHandler = (postId) =>
{
if(postId) {
// dispatch(boardSelected(postId));
getOnePost(postId)
}
}
...
}
This code uses axios.get to receive post information.
and I want to use api's return to global state(Redux state).
const getOnePost = async (id) => {
try {
const response = await axios.get(`/api/v1/post/${id}`);
const getOnePostData = await response.data;
return getOnePostData //return data
} catch(error) {
alert(error.response.data.message);
return Promise.reject(error)
}
}
const postClickHandler = (postId) =>
{
if(postId) {
getOnePost(postId).then((response)=>{
return{...selected, selected: response} //But Seleted: {}
})
}
}
Axios is a Promised-based JavaScript library that is used to send HTTP requests,
you have to get the promise result in the then method .
try this
const Board = () => {
...
const {selected} = useSelector(state => state.board);
// In Redux reducer ->
// const initialState = {
// selected : {}
// }
const getOnePost = async (id) => {
try {
const response = await axios.get(`/api/v1/post/${id}`);
response.then(function (rec) {
selected = rec.data //
//here update you state
console.log(selected)
}).catch(function (error) {
console.log(error);
});
} catch(error) {
alert(error.response.data.message);
return Promise.reject(error)
}
}
const postClickHandler = (postId) =>
{
if(postId) {
// dispatch(boardSelected(postId));
getOnePost(postId)
}
}
...
}
You can handle promise by using .then()
Try to initialize selected like below :
const response = await axios.get(`/api/v1/post/${id}`).then( response => {
selected = response
})
I don't know what kind of data is it. So, try to log response data, and use it.

How to handle "Promise { <pending> }" in javascript

I have this function in javascript
const getData = async() => {
try {
const serviceResponse = await someService("userId")
return serviceResponse
} catch (error) {
console.log(error);
}
}
const data = getData()
console.log(data)
Whenever I am running this I am getting this in console
Promise { <pending> }
But when I am print data in the function itself I am getting the desired value
const getData = async() => {
try {
const serviceResponse = await someService("userId")
console.log.(serviceResponse)
} catch (error) {
console.log(error);
}
}
getData()
The following function is what I am importing from defined in another another
exports.someService = async(date,locationId,workerType) => {
const value = await Attendance.find({})
return value
}
Please can someone explain what is happening ?
you need to await the promise from getData() too -
const data = await getData()

What is the correct way to export an Async function module?

I have a file asyncAwait.js that has a simple function:
async function doStuff() {
return(`Function returned string.`);
}
module.exports.doStuff = doStuff;
In another module, testing.js, I invoke and all works as expected:
var functions = require(`./functions`);
(async () => {
const test = await functions.asyncAwait.doStuff();
console.log(test);
})();
This logs "Function returned string." to the console.
All good.
However, if I use axios in asyncAwait.js:
const axios = require(`axios`);
async function doStuff(parameter) {
const url = `https://jsonplaceholder.typicode.com/posts/1`;
const getData = async url => {
try {
const response = await axios.get(url);
const data = response.data;
console.log(data);
} catch (error) {
console.log(error);
}
};
return(getData(url));
}
module.exports.doStuff = doStuff;
Then in testing.js:
var functions = require(`./functions`);
(async () => {
const test = await functions.asyncAwait.doStuff();
console.log(test);
})();
This logs undefined.
Why does the function call return undefined in the second example?
In your example getData has no return. In this case your function will implicitly return undefined. To fix it you could change that function to the following:
const getData = async url => {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
return error
}
};
module.exports.doStuff = doStuff;
May I suggest you :
module.exports=doStuff;
Or
exports.doStuff
and maybe but not sure what you're trying to achieve
replace
return(getData(url));
by
return(()=>{return getData(url)});

How can I manage to make diffrent request after first request with failed status

I try to fetch some object, but the problem is that I need to check first if there ist any object on cache endpoint, if not I should do normal fetching from regular endpoint.
So far I only managed to do fetching from:
Normal endpoint and set everything on state,
Cache endpoint and set everything on state
Any attempts to mix both methods ended in failure :(
How can I mix this two methods?
const getCache = async () => {
try {
const apiCall = await fetch(fetchCacheEndpoint)
const data = await apiCall.json()
return data
} catch (e) {
console.log(e);
}
}
const pageOne = getCache().then((result) => {
const convertedOBj = result.doSomeSeriousStuff()
this.setState({
desiredObj: convertedOBj
})
})
I expected to do something like this
const getCache = async () => {
try {
const apiCall = await fetch(fetchCacheEndpoint)
const data = await apiCall.json()
return data
} catch (e) {
console.log(e);
}
}
let convertedOBj
const pageOne = getCache().then((result) => {
if ((result === undefined) || (!result) || (result && !result.length > 0)) {
const makeRegularFetch = async () => {
const regularFetch = await fetch(regularEndPoint)
const data = await regularFetch.json()
}
const pageTwo = makeRegularFetch ().then((result) => {
convertedOBj = result.doSomeSeriousStuff()
this.setState({
desiredObj: convertedOBj
})
})
} else {
convertedOBj = result.doSomeSeriousStuff()
this.setState({
desiredObj: convertedOBj
})
}
})
After first fetch (getCache) is failed there is another fetch (makeRegularFetch) to second endpoint which is always fine, but only in the case when first(getCache) return empty object or just any kind of error
How can I handle this kind of action?
From what I can see in your second part of your code, you never execute your pageOne function.
Try pageOne() after your definition.
However I made a fiddle on stackblitz for your case: https://stackblitz.com/edit/js-eufm8h
If you don't understand something, feel free to ask.

Async await does not wait for function to finish

I use fetch to get data for each element of an array. Those values are pushed into an array and I want to return the max of those values once all values are fetched.
For that I used a promise:
async function init() {
await maxWaste(nut0Codes).then(response => {
console.log(response);
});
}
function maxWaste(nutCodes) {
return new Promise(resolve => {
let waste = [];
nutCodes.forEach((element) => {
let query = queryMaxWaste(element);
fetch(address + encodeURIComponent(query))
.then(response => {
return response.json();
})
.then(response => {
waste.push(response.results.bindings[0].wasteGeneration.value);
console.log(waste);
});
});
let maxWaste = Math.max(waste);
resolve(maxWaste);
});
}
I am not sure where my mistake is but the resolve happens before the fetch is done :
I receive the zero from the console.log(response) and I don't know why it is not working.
Any advice would be appreciated!
If you're going to write code that uses async, you should actually leverage async. If this needs to be run synchronously-ish, you can await within a for loop. If you want them all to run simultaneously, use a map and Promise.all.
async function init() {
const response = await maxWaste(nut0Codes);
console.log(response);
}
async function maxWaste(nutCode) {
const waste = [];
for (const element in nutCode) {
const query = queryMaxWaste(element);
const response = await fetch(address + encodeURIComponent(query));
const json = await response.json();
waste.push(json.results.bindings[0].wasteGeneration.value);
console.log(waste);
}
const maxWaste = Math.max(waste);
return maxWaste;
}
You could also try writing it like this so that you don't wait for each response to complete before running the next fetch:
async function init() {
const response = await maxWaste(nut0Codes);
console.log(response);
}
async function maxWaste(nutCode) {
const waste = await Promise.all(nutCode.map(async element => {
const query = queryMaxWaste(element);
const response = await fetch(address + encodeURIComponent(query));
const json = await response.json();
return json.results.bindings[0].wasteGeneration.value;
}));
return Math.max(waste);
}

Categories

Resources