Can't get data out of Axios - react-native

Can't get my data from the request out of Axios. My console log prints the correct but when I try to set it to a variable or return it I get nothing.
static getGroupByID(groupID) {
var self = this;
var group = '';
axios.post((GRAPHQL_END_POINT), {
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}`enter code here`
})
.then(res => {
console.log(res.data.data.getGroup.name);
self.group = res.data.data.getGroup.name;
})
.catch(err => console.log(err))
return group;
}

static getGroupByID(groupID) {
var self = this;
var group = '';
return axios.post((GRAPHQL_END_POINT), { <-- Return your promise
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}`enter code here`
})
.then(res => {
console.log(res.data.data.getGroup.name);
return res.data.data.getGroup.name; <--- Return your data and use getGroupById(...).then(...)
})
.catch(err => console.log(err))
}

The query is async, your function returns an empty group = '', set the value in state or use await. The function returns before the query finish, you can for the query to finish using async/await.
static async getGroupByID(groupID) {
try {
const res = await axios.post(GRAPHQL_END_POINT, {
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}
});
const { data } = await res;
return data;
} catch (error) {
console.log(error);
}
}
Or you can just return the promise and handle it where you are calling the function.
static getGroupByID(groupID) {
return axios.post(GRAPHQL_END_POINT, {
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}
});
}

Related

Express how to append queries with the same property?

Right now im trying to write a query deconstruction, it should look like this
describe("Deconstruct query params", () => {
it("should deconstruct the desired query param such as id=1,2,3,4 into id=1&id=2&id=3&id=4", async () => {
const req: RequestCustom = {
extra : {
user: {}
},
query: {
id: "1,2,3,4",
},
};
const res = {};
const next = jest.fn();
await deconstructQueryParams(["id"])(
(req as unknown) as express.Request,
res as express.Response,
next
);
expect(req.query).toEqual(
"id=1&id=2&id=3&id=4"
);
});
});
For this I try and use
export const deconstructQueryParams = (params: Array<string>) => async (
req: Request,
res: Response,
next: NextFunction
) => {
params.forEach((param) => {
if (req.query[param]) {
const paramArr = req.query[param].split(",");
delete req.query[param]
paramArr.forEach((value: string) => {
req.query.append(param, value); //append doesnt exist
});
}
});
next();
}
The problem with this, is that I cant use
req.query.id=1
req.query.id=2
.....
Because those queries will be replaced, when I need "id=1&id=2&id=3&id=4"
But apparently req.query.append doesnt exist, so I cant duplicate the query properties? How can I do so?

React Native how get data from asynchrone function

I try to get data from an asynchronestorage function
_retrieveData = async () => {
var test = await AsyncStorage.getItem('myitem')
return test
}
_generateRandomCards() {
console.log(this._retrieveData())
}
But that return :
Promise {
"_U": 0,
"_V": 0,
"_W": null,
"_X": null,
}
Edit : After the answer of Václav Ryska, i can change it with setstate, but that reload once if i call getValue from componentDidMount, and infinite loop in my generaterandomcards function.
My code :
componentDidMount() {
this.getValue()
}
getValue = async () => {
AsyncStorage.getItem('key')
.then(data => {
this.setState({deckDrawToday: true});
})
}
_generateRandomCards() {
console.log(this.state.deckDrawToday)
...
this._generateRandomCardsTrue()
...
return (
this._generateViewCards()
)
}
_generateRandomCardsTrue() {
...
}
_generateViewCards() {
...
}
render() {
return (
this._generateRandomCards()
)
}
return is not a valid statement for async functions, you gotta set the value in a callback to a variable
this.state = {
value: null
}
componentDidMount() {
this.getValue();
}
getValue = async () => {
AsyncStorage.getItem('key')
.then(data => {
this.setState({value: data});
console.log(data)
})
}
use console.log(await this._retrieveData()) since your function is async

Await return undefined

I am working with express server and trying to read data from file and return it to different function.
My code structure looks like this:
async function getUser(req) {
fs.readFile(cfg.fileDefaults, (err, defaults) => {
do something
return user;
}
}
module.exports = {getUser}
In controller I call that function
static getTable(req, res, next) {
async function search() {
user = await getUser(req); //return undefined
getUser(req).then((a) => {
console.log(a); //second try, return undefined
})
}
search();
}
How should I call it correctly?
const fs = require('fs')
function getUser(req) {
return new Promise((resolve, reject) => {
fs.readFile(cfg.fileDefaults, (err, defaults) => {
//do something
const user = { hellow: 'world' }
resolve(user)
})
})
}
module.exports = { getUser }
In controller
static getTable(req, res, next) {
async function search() {
user = await getUser(req); // return { hellow: 'world' }
res.end(JSON.stringify(user, null, ' '))
}
search().catch((err) => {
console.log('err',err)
res.status(500)
res.end('error')
})
}

I am getting `Can not use keyword 'await' outside of a async function` within an Async function.. React-native

I am having an issue with async await for my AsyncStorage function within my React-native application. The error I'm getting is:
Can not use keyword 'await' outside of a async function
As you can see below, it's obvious that await is within the function. What am I doing wrong to get this error?
_retrieveData = async function (location) {
try {
var index = await AsyncStorage.getItem(location, (err, result) => result).then(result => result).catch(error=>console.log(error))
if (index !== null) {
return JSON.parse(index)
}
} catch (error) {
return null
}
};
_storeData = async function(location, value) {
try {
await AsyncStorage.set(location, JSON.stringify(value));
} catch (error) {
console.log(error)
}
};
Use ES6 arrow functions
const _retrieveData = async location => {
try {
let index = await AsyncStorage.getItem(location)
if (index !== null) {
return JSON.parse(index);
}
} catch (error) {
return null;
}
};
const _storeData = async (location, value) => {
try {
await AsyncStorage.set(location, JSON.stringify(value));
} catch (error) {
console.log(error);
}
};
Make them as an arrow functions
_retrieveData = async location => {
try {
let index = await AsyncStorage.getItem(location)
if (index !== null) {
return JSON.parse(index);
}
} catch (error) {
return null;
}
};
_storeData = async (location, value) => {
try {
await AsyncStorage.set(location, JSON.stringify(value));
} catch (error) {
console.log(error);
}
};

How to use transaction by sequelize in my node js

While converting legacy long sql procedure to sequelizer, I met trouble to make transaction to my async functions.
I read sequelizer's transaction documents. But failed to understand clearly.
Here is my code.
const models = require('../models/models.js');
const sequelize = models.Sequelize;
async function isExistFeeHist(dansokSeqNo) {
log.debug("isExistFeeHist()");
let feeHist = await models.FeeHist.findOne({
where: {
DansokSeqNo: dansokSeqNo,
FeeStatus: {[Op.ne]: null}, //is not null
DelYN: false
}
});
return !!feeHist;
}
async function isPaid(dansokSeqNo) {
...
}
async function getNextDansokHistSerialNo(dansokSeqNo) {
...
}
async function getVBankSeqNo(dansokSeqNo) {
...
}
async function updateVBankList(dansokSeqNo, vBankSeqNo) {
...
}
//check if can cancel
async function checkCancelable(dansokSeqNo) {
log.debug("checkCancelable() ", dansokSeqNo);
if (await isExistFeeHist(dansokSeqNo)) {
let e = {status:400, message: 'already imposed dansokSeqNo ' + dansokSeqNo };
return Promise.reject({status:400, message: e.message });
}
if (await isPaid(dansokSeqNo)) {
let e = {status:400, message: 'already paid dansokSeqNo ' + dansokSeqNo };
return Promise.reject({status:400, message: e.message });
}
return Promise.resolve();
}
....
async function doCancel(dansokSeqNo, cancelCauseCode, histMemo) {
try {
await checkCancelable(dansokSeqNo);
//// <== Here I want to start transaction
let nextDansokSerialNo = await getNextDansokHistSerialNo(dansokSeqNo);
let dansokHist = await insertNewDansokHist(dansokSeqNo, nextDansokSerialNo, cancelCauseCode, histMemo);
await updateDansokHist(dansokSeqNo, cancelCauseCode);
let vBankSeqNo = await getVBankSeqNo(dansokSeqNo);
if (vBankSeqNo > 0) {
await updateVBankList(dansokSeqNo, vBankSeqNo);
let vBankList = await getVBankList(dansokSeqNo);
}
// <== Here I want to commit transaction
} catch (e) {
// <== Here I want to rollback transaction
return Promise.reject({status:e.status, message: e.message });
}
}
exports.cancelDansok = function (req, res) {
res.setHeader("Content-Type", "application/json; charset=utf-8");
...
jwtAcessAuth(accessToken)
.then((decoded) => {
log.info("jwt success, ", decoded);
worker = decoded.loginName;
return doCancel(dansokSeqNo, cancelCauseCode, histMemo);
})
.then(() => {
res.status(200).json({ message: 'cancelDansok success.' });
})
.catch(e => {
return res.status(e.status).json(e);
});
};
My function is assembled with several async functions. And it need to bind one transaction.
What is the best practice to use transaction in my several async await functions?
Here is the best example provided by Sequlize for Transaction :
All you need to care is pass transaction to next level of chaining
return sequelize.transaction(function (t) {
// chain all your queries here. make sure you return them.
return User.create({
firstName: 'Abraham',
lastName: 'Lincoln'
}, {transaction: t}).then(function (user) {
return user.setShooter({
firstName: 'John',
lastName: 'Boothe'
}, {transaction: t});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
});
For more details : Transactions