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
Related
I'm trying to only show the disclosure screen the first time the user logs in by using AsyncStorage. Currently getData is returning a Promise and it goes straight to the landing screen on first login.
Could I get some help to get this functioning the way I want it to?
This is my login handler:
const key = 'key';
const storeData = async () => {
try {
await AsyncStorage.setItem('key', 'true');
} catch (error) {
// saving failed
console.log(error.message);
}
};
const getData = async key => {
let value = '';
try {
value = await AsyncStorage.getItem(key);
return JSON.parse(value);
} catch (e) {
console.log(error.message);
}
};
const _loginHandler = () => {
if (userName == '' || password == '') {
console.log('gagagagagagagagagagagagagagagagag');
} else {
setShowLoading(true);
const payload = {userName: userName.trim(), password: password.trim()};
setUserName('');
setPassword('');
_UserLoginHandler(payload).then(data => {
setShowLoading(false);
if (data.error) {
GlobalShowSnackBar(data.error);
} else {
setTimeout(() => {
setUserId(data);
//props.navigation.replace(getData("key")?'Landing':'Disclosure')
console.log('Key Value ' + JSON.stringify(getData('key'))); <-- this outputs Key Value {"_U":0,"_V":0,"_W":null,"_X":null}
if (getData('key')) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
}, 500);
}
});
}
};
I got it to work with
getData('key').then(val => {
if (val) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
});
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 want to join three res.data (carsIn,PositionUsed,position),this res.data I get it by axios.get
carsIn(id,username,useraddress,userphone,plate)
PositionUsed(id_pos,id_car,enterdate)
position(id_pos,name)
I tried this solution but I need to refresh 3 time to get data in array mergedd
any solution ?
I want to get mergedd (username,useraddress,userphone,plate,enterdate,name)
export default {
name: "Courses",
data() {
return {
carsIn: [],
PositionUsed:[],
merged:[],
positions:[],
mergedd:[],
message: "",
INSTRUCTOR: "in28minutes"
};
},
computed: {
currentUser() {
return this.$store.state.auth.user;
}
},
mounted() {
if (!this.currentUser) {
this.$router.push('/login');
}
},
methods: {
refreshCourses() {
clientService.retrieveAllCarsIn(this.INSTRUCTOR)
.then((res) => {
this.carsIn= res.data;
});
clientService.retrieveAllPositionOcp(this.INSTRUCTOR)
.then((res) => {
this.PositionUsed= res.data;
for(let i=0; i<this.carsIn.length; i++) {
this.merged.push({
...this.carsIn[i],
...(this.PositionUsed.find((itmInner) =>
itmInner.id_car === this.carsIn[i].plate))}
);
}
});
clientService.retrieveAllPositions(this.INSTRUCTOR)
.then((res) => {
this.positions = res.data;
for(let i=0; i<this.merged.length; i++) {
this.mergedd.push({
...this.merged[i],
...(this.positions.find((itmInner) => itmInner.id_pos
=== this.merged[i].id_pos))}
);
}
});
}
},
created() {
this.refreshCourses();
}
}
This is the best solution but it will only work if clientService.retrieveAllCarsIn , clientService.retrieveAllPositionOcp and clientService.retrieveAllPositions are promises
refreshCourses() {
Promise.all([clientService.retrieveAllCarsIn(this.INSTRUCTOR) , clientService.retrieveAllPositionOcp(this.INSTRUCTOR)] , clientService.retrieveAllPositions(this.INSTRUCTOR)).then((response) =>{
this.carsIn= response[0].data;
this.PositionUsed= response[1].data;
this.positions = response[2].data;
}).catch((err) =>{
//error handler
}).finally(() =>{
})
}
Seems like the you can rewrite your function something like this:
refreshCourses() {
// Get data for all 3 requests at the same time
const [courses, pos, positions] = Promise.all([clientService.retrieveAllCarsIn(this.INSTRUCTOR), clientService.retrieveAllPositionOcp(this.INSTRUCTOR), clientService.retrieveAllPositions(this.INSTRUCTOR)]);
// Now iterate over courses
this.mergedd = courses.map(({
id,
namecourse,
desc,
plate
}) => {
// Get date from pos array
const {
date,
id_position
} = pos.find(p => p.id_car === plate); // Or p.id_course === id
// Get nameposition from positions array
const {
nameposition
} = positions.find(p => p.id === id_position);
const out = {
id,
namecourse,
desc,
date,
nameposition
}
});
}
Here is my code and I use asyncstorage to set user's name. I get this error
I get a warning saying Can't perform a React state update on an unmounted component. it indicates a memory leak. cancel and asynchronous tasks in the componentWillUnmount method.
UNSAFE_componentWillMount(){
this.getName()
this.disableSEND()
}
getName = async () => {
let value = 'userName'
try {
await AsyncStorage.setItem('NAME', value))
} catch (e) {
Alert.alert(e.message)
}
}
disableSEND = async () => {
let value = await AsyncStorage.getItem('SENDDISABLED')
this.setState({ switch: value == 'true' ? true : false })
let disableBtn = AsyncStorage.getItem('DISABLEBTN')
this.setState({ disableBtn: disableBtn == 'false' ? false : true })
}
disableMSG = async (value) => {
try {
AsyncStorage.setItem('DISABLEMSG', value.toString())
} catch (e) {
Alert.alert(e.message)
}
}
disableBtn = async (disableBtn) => {
try {
AsyncStorage.setItem('DISABLEBTN', disableBtn.toString())
} catch (e) {
Alert.alert(e.message)
}
}
render() {
return (
<DrawerContentScrollView {...this.props}>
</DrawerContentScrollView>
);
}
}
})
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
}
});
}