AsyncStorage.getItem() doesn't seem to work - javascript

When I try to set a value via AsyncStorage.getItem(), I cannot request it back.
let tokenData = null;
const getData = async () => {
let token;
try {
token = await AsyncStorage.getItem('token');
tokenData = JSON.parse(token);
} catch (e) {
// error reading value
}
};
I have set item like follows
const setLoginLocal = async loginData => {
try {
let token = loginData.headers.authorization;
let headerToken = ['token', JSON.stringify(token)];
let user = ['user', JSON.stringify(loginData.data)];
await AsyncStorage.setItem([user, headerToken]);
} catch (err) {
console.log(err);
}
};

If you want to store data you have to setItem like this:
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
console.log(error);
}
};
then you can retrieve it with getItem like this:
const getData = async key => {
try {
const data = await AsyncStorage.getItem(key);
if (data !== null) {
console.log(data);
return data;
}
} catch (error) {
console.log(error);
}
};

const setLoginLocal = async loginData => {
try {
let token = loginData.headers.authorization;
let headerToken = ['token', JSON.stringify(token)];
let user = ['user', JSON.stringify(loginData.data)];
await AsyncStorage.setItem([user, headerToken]);
} catch (err) {
console.log(err);
}
};

Related

Node.js Error ( Cannot GET /api/events/100 ) ( single Get , Post ) SQL Server 2019

i create API With Node.js and SQL Server and its working normally with Get All Data I tested it with postman (200)
.. index.js page
const getEvents = async () => {
try {
let pool = await sql.connect(config.sql);
const sqlQueries = await utils.loadSqlQueries('events');
const eventsList = await pool.request().query(sqlQueries.eventslist);
return eventsList.recordset;
} catch (error) {
console.log(error.message);
}
}
and the eventController.js page
const getAllEvents = async (req, res, next) => {
try {
const eventlist = await eventData.getEvents();
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
and eventlist.sql
SELECT [employee_id]
,[first_name]
,[last_name]
,[email]
,[phone_number]
,[hire_date]
,[job_id]
,[salary]
,[manager_id]
,[department_id]
FROM [sales].[dbo].[employees]
******************* But with read single post (Error)
index.js page
const getById = async(eventId) => {
try {
let pool = await sql.connect(config.sql);
const sqlQueries = await utils.loadSqlQueries('events');
const event = await pool.request()
.input('employee_id', sql.Int, eventId)
.query(sqlQueries.eventbyId);
return event.recordset;
} catch (error) {
return error.message;
}
}
And and the eventController.js page
const getEvent = async (req, res, next) => {
try {
const eventId = req.params.id;
const event = await eventData.getById(eventId);
res.send(event);
} catch (error) {
res.status(400).send(error.message);
}
}
and eventlbyId.sql
SELECT [employee_id]
,[first_name]
,[last_name]
,[email]
,[phone_number]
,[hire_date]
,[job_id]
,[salary]
,[manager_id]
,[department_id]
FROM [sales].[dbo].[employees] WHERE [employee_id]=#employee_id
the Res From postman
<pre>Cannot GET /api/events/100</pre>

Async function, do something after the map function is finished

async function testing(summoner_name) {
try {
var match;
let summoner = {
name: [summoner_name],
};
const id = await fetchAccountID(summoner_name);
const matchList = await fetchMatches(id);
Object.keys(matchList.matches).map((key, i) => {
setTimeout(async function () {
match = await fetchMatch(matchList.matches[key].gameId);
summoner = await getMatchStats(
match,
matchList.matches[key].champion,
summoner
);
}, i * 100);
});
} catch (error) {
console.log(error);
}
}
I would like to do something after the map function is done iterating over all the keys, how can I achieve that?
Do you mean this?
async function testing(summoner_name) {
try {
let summoner = {
name: [summoner_name],
};
const id = await fetchAccountID(summoner_name);
const matchList = await fetchMatches(id);
//Promise in Serial
for (const key of Object.keys(matchList.matches)) {
const match = await fetchMatch(matchList.matches[key].gameId);
summoner = await getMatchStats(
match,
matchList.matches[key].champion,
summoner
);
}
} catch (error) {
console.log(error);
}
}

nodejs javascript promise resolve

I can't seem to figure out how to save the results of SomeQuery promise. Essentially I would like to take the value in res and pipe it into parseQuery function and return the final results. How do I make the parsed result accessible to an APIs response.
const neo4j = require('neo4j-driver')
var parser = require('parse-neo4j')
const astria_queries = require('./astriaQueries')
const uri = 'bolt://astria_graph:7687'
const user = 'xxx'
const password = 'xxx'
const someQuery = (query) => {
// run statement in a transaction
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
const session = driver.session({ defaultAccessMode: neo4j.session.READ })
const tx = session.beginTransaction()
tx.run(query)
.then((res) => {
// Everything is OK, the transaction will be committed
parseQuery(res)
})
.then(() => {
// Everything is OK, the transaction will be committed
})
.catch((e) => {
// The transaction will be rolled back, now handle the error.
console.log(e)
})
.finally(() => {
session.close()
driver.close()
})
}
const parseQuery = (result) => {
try {
const test = parser.parse(result)
console.log(test)
} catch (err) {
console.log(err)
}
}
module.exports = {
someQuery,
}
It finally clicked with me. Here is the solution I came up with. Hopefully it will help others. If there is a better way please let me know. Thank you #fbiville for you help.
async actions
const neo4j = require('neo4j-driver')
var parser = require('parse-neo4j')
const astria_queries = require('./astriaQueries')
const uri = 'bolt://astria_graph:7687'
const user = 'neo4j'
const password = 'neo'
async function getRecords(query) {
// run statement in a transaction
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
const session = driver.session({ defaultAccessMode: neo4j.session.READ })
const tx = session.beginTransaction()
try {
const records = await tx.run(query)
const parseRecords = await parseQuery(records)
return parseRecords
} catch (error) {
console.log(error)
} finally {
session.close()
driver.close()
}
}
async function parseQuery(result) {
try {
const parsedRes = await parser.parse(result)
// console.log(parsedRes)
return parsedRes
} catch (err) {
console.log(err)
}
}
// getRecords(astria_queries.get_data_sources)
module.exports = {
getRecords,
}
api send()
exports.get_data_sources = async (req, res) => {
try {
queryFuns.getRecords(astria_queries.get_data_sources).then((response) => {
res.send(response)
})
} catch (error) {
res.status(500).send(error)
console.log(error)
}
}

How to get the result of async / await function?

I would like to return an object from the the async / await function A to pass it to another function.
Currently what I get as a result is Promise{ <pending> }' or undefined.
function A:
const parseRss = data => data.forEach(rssLink => {
const getFeed = async () => {
try {
const feed = await rssParser.parseURL(rssLink.rss);
const emailContent = {
emailBody: {
title: feed.title,
content: []
}
}
feed.items.forEach(item => {
feedObj.emailBody.content.push(`${item.title} : ${item.link}`)
});
return emailContent;
} catch (e) {
console.error(e);
}
};
return (async () => {
return await getFeed();
})();
});
Function B:
try {
const data = await getDataWithRss();
const emailData = await parseRss([{rss:'http://reddit.com/.rss'}]); // emailData is undefined
return formatEmail(emailData);
} catch (error) {
console.log(error);
}
How do I return emailContent from function A to use it in function B?
Thanks!
Since you made getFeed as async, no need another async. You are looping through, so return an array of promises. Once the you call use Promise.all to resolve. Since there could be multiple urls to fetch.
const parseRss = (data) =>
data.map((rssLink) => {
const getFeed = async () => {
try {
const feed = await rssParser.parseURL(rssLink.rss);
const emailContent = {
emailBody: {
title: feed.title,
content: [],
},
};
feed.items.forEach((item) => {
feedObj.emailBody.content.push(`${item.title} : ${item.link}`);
});
return emailContent;
} catch (e) {
console.error(e);
}
};
return getFeed();
});
try {
const data = await getDataWithRss();
const emailData = await Promise.all(parseRss([{rss:'http://reddit.com/.rss'}])); // emailData is undefined
return formatEmail(emailData);
} catch (error) {
console.log(error);
}
await will not work inside a forEach loop. Use a for...in loop instead.
actually, getFeed() is not necessary inside inner scope, you can use async in map callback:
const parseRss = data => data.map(async rssLink => {
const feed = await rssParser.parseURL(rssLink.rss);
const emailContent = {
emailBody: {
title: feed.title,
content: []
}
};
feed.items.forEach(item => {
feedObj.emailBody.content.push(`${item.title} : ${item.link}`)
});
return emailContent;
});

response.text is not a function while building react-native app

I'm trying to build a react-native app with expo and while trying to sign up I get the following error message stemming from my api.js file:
response.text is not a function. (In 'response.text()', 'response.text' is undefined).
Here is my code:
const BASE_URL = "my local IP:5000";
export const api = async (url, method, body = null, headers = {}) => {
try {
const endPoint = BASE_URL.concat(url);
const reqBody = body ? JSON.stringify(body) : null;
const fetchParams = {method, headers};
if((method === "POST" || method === "PUT") && !reqBody) {
throw new Error("Request body required");
}
if(reqBody) {
fetchParams.headers["Content-type"] = "application/json";
fetchParams.body = reqBody;
}
const fetchPromise = fetch(endPoint, fetchParams);
const timeOutPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject("Request Timeout");
}, 3000);
});
const response = await Promise.race([fetchPromise, timeOutPromise]);
return response;
} catch (e) {
return e;
}
}
export const fetchApi = async (url, method, body, statusCode, token = null, loader = false)
=> {
try {
const headers = {}
const result = {
token: null,
success: false,
responseBody: null
};
if(token) {
headers["x-auth"] = token;
}
const response = await api(url, method, body, headers);
console.log(response);
if(response.status === statusCode) {
result.success = true;
if(response.headers.get("x-auth")) {
result.token = response.headers.get("x-auth");
}
Here is response.text()
let responseBody;
const responseText = await response.text();
//const responseText = await response.json();
try {
responseBody = JSON.parse(responseText);
} catch (e) {
responseBody = responseText;
}
result.responseBody = responseBody;
return result;
}
Here is response.text()
let errorBody;
const errorText = await response.text();
//const errorText = await response.json();
try {
errorBody = JSON.parse(errorText);
} catch (e) {
errorBody = errorText;
}
result.responseBody = errorBody;
console.log(result);
throw result;
} catch (error) {
return error;
}
}
Any help would be immensely appreciated.

Categories

Resources