axios.get response not getting assigned to variable - vuejs2

I have been researching this question for some time and have not found an answer.
I am using axios.get to return the userID. I am getting the correct response - I get a number for userID when doing console.log(response.data); However, when I try to assign response.data to a local variable so I can return it, it is not getting set.
( I also tried defining userID globally under data and then referencing it as userID.this but it didn't help.)
I've looked at other answers such as this one: Axios can't set data but they didn't work for me.
Any help is appreciated. Thanks in advance. (code below)
edit: I also looked at this question: How do I return the response from an asynchronous call? but it didn't add anything for me. It suggested using promises and the then block but I did that already and it's still not working.
retrieveUserID: function()
{
var userID=0;
this.axios.get('getUserID.php' , {
params: {
username: this.currentUser
} })
.then(response => {
console.log("retrieveUserID:response.data = " + response.data);
userID=response.data;
} )
.catch((error )=> {this.submitSessionFailure(error);});
return userID ; // staying zero
}

Try this...
retrieveUserID: function()
{
this.axios.get('getUserID.php' , {
params: {
username: this.currentUser
}
})
.then(response => {
var userID=0;
console.log("retrieveUserID:response.data = " + response.data);
userID=response.data;
} )
.catch((error )=> {this.submitSessionFailure(error);});
return userID ; // staying zero
}

Related

Unable to set useState variable in async method and console log it

Im working with my friends on a app project and we find an issue many times when we tring to set a use state and the console log the variable, i've looking for a solution in the website and saw that the reason is that the usestate is an async awiat which means the variable that i set in the use state isn't immidatly set in it, so i tried many solution that i found in the websites but none of them work for me.
in the screenShot you can see that the json variable is in console log before and the set varaible doesn't show after the setActiveUser , any help?
Thanks!
If you want to do something upon setting state then your best bet is to use the useEffect hook from React and adding your state in the dependency array. This will then call the function in your useEffect every time the state changes. See below a rough example:
import { Text } from 'react-native';
const MyComponent = () => {
const [activeUser, setActiveUser] = useState(null);
useEffect(() => {
// This should log every time activeUser changes
console.log({ activeUser });
}, [activeUser]);
const fetchAuthentication = async user => {
var flag = false;
await fetch('/api/authUser/', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user),
})
.then(res => {
res.ok && (flag = true);
return res.json();
})
.then(json => {
if (flag) {
setActiveUser(json);
}
})
.catch(error => console.error(error));
return flag;
};
return <Text>Hi</Text>;
};
Full documentation: https://reactjs.org/docs/hooks-effect.html

What am I missing with this API connection request string?

I have my api_key in a ".env". I could be overthinking it. Here's my code as it currently stands, works without hiding the api_key. My syntax is incorrect when I pull from process.env.API_KEY.
function call_api(finishedAPI, ticker) {
request('https://cloud.iexapis.com/stable/stock/' + ticker + '/quote?token= + 'api_key', { json: true }, (err, res, body) => {
if (err) {return console.log(err);}
if (res.statusCode === 200){
finishedAPI(body);
};
});
};
I know there's a simpler way to do this and my research to google cues aren't firing on all cylinders. I'll buy you coffee or a tomato basil panini from Starbucks :-)
Should be. It also looks like your trying to use a callback incorrectly.
NOTE though, it's easy to tell you should always state the lang used. Just makes things easy for everyone.
function call_api(ticker, finishedAPI) {
request({url: 'https://cloud.iexapis.com/stable/stock/' + ticker + '/quote?token= + 'api_key'}, { json: true }, (err, res, body) => {
if (err) {return console.log(err);}
if (res.statusCode === 200){
finishedAPI(body);
};
});
};
function main(){
call_api(ticker, function(fromCallapi){
if(fromCallapi) console.log(fromCallapi);
})
}
A callback would be called within another method or operation, and would returned to caller once the operation is completed by, passing the process, variable, or method back to it's caller.
NOTE the param finishedAPI should be renamed as callback it best practice to indicate that the process, variable, or method will be returning the result back to caller. Please note, that overly using callbacks can be overall affect the performance of you application and can hang processes. Hope that helps
UPDATE
If you have plan on using .env you'll need to use require('dotenv').config(path: '/path/to/.env') once loaded for example to access a variable named VARIBLE_NAME, you would access the env variable using process.env.VARIBLE_NAME
function call_api(finishedAPI, ticker) {
request('https://cloud.iexapis.com/stable/stock/' + ticker + '/quote?token=' + API_KEY, { json: true }, (err, res, body) => {
if (err) {return console.log(err);}
if (res.statusCode === 200){
finishedAPI(body);
};
});
};

localStorage.getItem() always returns null even when value exists

Im not sure If I am doing something wrong or if I have a typo somewhere, but I am trying to compare dates in a vue project but the value I pull from my local storage always returns null even when I can see the value clearly exists when I check my local storage. so here is the set up.
after making a request I set the expires date in local storage like so
retrieveToken({ commit }, credentials) {
return new Promise((resolve, reject) => {
axios.post('/login', {
username: credentials.username,
password: credentials.password,
})
.then(response => {
const token = response.data.access_token
const date = new Date(moment().add(30, 'seconds').toDate());
localStorage.setItem('expires_on', date)
localStorage.setItem('access_token', token)
resolve(response)
})
.catch(error => {
console.log(error.response.data)
reject(error)
})
})
},
I can then see that the expires on has been placed in my local storage
I then want to use a getter to retrieve that value like so
tokenExpires() {
return localStorage.getItem('expires_on')
},
So i can use like this
computed: {
...mapGetters(['tokenExpires']),
},
methods: {
destroySessionIfTokenIsExpired() {
const current = new Date(moment())
const expires = this.tokenExpires
const currentDate = moment(current).format('YYYYMMDDHHMMSS')
const expiresDate = moment(expires).format('YYYYMMDDHHMMSS')
console.log(this.tokenExpires)
console.log(expiresDate)
if(currentDate >= expiresDate) {
this.$store.dispatch('destroyToken')
.then(() => {
this.$router.push('/login')
alert('Your Session Has Expired, Please Log Back In')
})
} else return;
}
}
but when I run this method and console.log(this.tokenExpires) it returns null and I am not sure why. If anybody can see what I am doing wrong please let me know!!
*Update, my issue is that I am trying to watch the routes and run a comparison of timestamps to see if the session is still valid but as pointed out, the getter does not have enough time to compute the value before the method runs, so any suggestions on how I could get around that would be awesome. here is the route watch method
watch: {
'$route': function(to, from) {
this.destroySessionIfTokenIsExpired()
}
},
thanks to #YongQuan I have this solution.
methods: {
...mapActions(['destroyToken']),
destroySessionIfTokenIsExpired() {
const expiresOn = localStorage.getItem('expires_on')
const expiresDate = moment(expiresOn).format('YYYYMMDDHHMMSS')
if(expiresOn == null) return;
const current = new Date(moment())
const currentDate = moment(current).format('YYYYMMDDHHMMSS')
if(currentDate >= expiresDate) {
this.$store.dispatch('destroyToken')
this.$router.push('/login')
} else return;
}
},
watch: {
'$route': function(to, from) {
this.destroySessionIfTokenIsExpired()
}
},
Instead of using a getter I just set the `localStorage.getItem('expires_on') to a variable inside the method. Thanks #YongQuan

how to get multiple fields from expo SecureStore

I am new to ES6 and react-native, trying to get multiple values from the SecureStore.
I think I am misunderstanding promises here ... global.userData is empty in the Promise.all(promises).then function. The relevant values do exist in the secure store
My code is:-
getUserData(fields) {
var promises = [];
var that = this;
global.userData = {};
function getField(field) {
return SecureStore.getItemAsync(field)
.then(res => {
console.log(field+"="+res); // this appears after the log below
global.userData[field] = res;
})
.catch(error => {
global.userData[field] = null;
});
}
fields.map(field => {
promises.push[getField(field)];
});
Promise.all(promises).then(function(v) {
console.log(global.userData); // this is empty
that.setState({ isReady: true }); // allow page to render
});
}
getUserData(["userId", "userName","etc"]);
My bad ... inadvertantly used
promises.push[getField(field)];
should have been:
promises.push(getField(field));
Suprised it wasn't detected as a syntax error ...

Why AsyncStorage getItem is returning null?

export const USER_KEY = "isLoggedIn";
export const phoneVerified = () => AsyncStorage.setItem(USER_KEY, 1);
export const userInfoVerified = () => AsyncStorage.setItem(USER_KEY, 2);
I have used the above functions to store the value and the below one to get the value.
export const isSignedIn = () => {
return new Promise((resolve, reject) => {
AsyncStorage.getItem(USER_KEY)
.then(res => {
console.log("from isSignedIn : "+res); //res is showing null.
if (res !== null) {
resolve(res);
} else {
resolve(0);
}
})
.catch(err => reject(err));
});
};
Why this always returns null? I was trying async/await but still getting null. I think somehow the data is not storing.
I'm afraid you can only store strings. Please refer to this React Native AsyncStorage storing values other than strings and this https://facebook.github.io/react-native/docs/asyncstorage.html#setitem
Thanks.
As answered by #Vishu Bhardwaj AsyncStorage accepts only string. So you can use JSON.stringify() and JSON.parse() in such cases.
I was stuck with this stupid problem for almost one week, no other way that is suggested in all communities worked for me, but then I found something that is built of react-native which its setState() callback function: https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296.
so the only way that I guarantee that it's the only secure way so far is this that u use the setState() function in your promise and everything that you need to run, put them on a function and call it for the setState() callback function , this is only way you can make sure yourself that you neither get null nor never calling the function . Here I'm going to provide an example of it which this.tokeToServer() is my function which it's used as a callback function.
try {
AsyncStorage.getItem('firebase_token',(err,item) => {
if (item) {
this.setState({
firebase_token: item,
}),this.tokenToServer();
}
});
} catch (error) {
console.log("Error retrieving data" + error);
}
As presented by friend Abdu4, I had the same problem for 4 days and searching for different sites and forums. Attempts with async/await and others, even though you should use these options, the one you completed and really worked was to assign the value through setState by callback
try {
AsyncStorage.getItem('TOKEN_KEY',(err,item) => {
if (item) {
setToken({
Token: item,
});
}
});
} catch (error) {
console.log("Error retrieving data" + error);
}