How to use AsyncStorage in React-Native - javascript

I'm creating an Android App in React-Native.
This is my question:
I have basically 5 pages to manage the user:
1) Authentication ( in which I give the possibility to go to the Login or the SignUp)
2) Login Page
3) SignUp Page. In this page i set the value and then they are passed to the userPage.
4) User page. In this page I have the fetch to do a signup.
5) HomepageUser
In the User page I have the 2 function :
AsyncStorage.setItem
AsyncStorage.getItem
Like this
static async saveLoggedInUser(value) {
try {
await AsyncStorage.setItem("#loggedInUser", JSON.stringify(value));
} catch (error) {
console.log(error.message);
}
}
static async getUserLoggedIn() {
try {
return await AsyncStorage.getItem("#loggedInUser");
} catch (error) {
console.log(error.message);
return null;
}
}
Now My First page is the Authentication, how can I check if an user is already authenticated and then direct it to the HomepageUser??
Thanks you a lot!

On successful login you need to set user token in the Sign in page,
try {
await AsyncStorage.setItem('token', usertoken);
} catch (error) {
// Error saving data
}
Inside the componentDidMount method of your first page you need to check whether user token is set or not,
componentDidMount = async() =>{
try {
const value = await AsyncStorage.getItem('token');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
}
if token exist navigate to Home page or redirect to Sign in page.
There is an excellent documentation on Authentication flows with React navigation. You can check that if you are using React navigation for routing.
https://reactnavigation.org/docs/en/auth-flow.html

Related

Nextjs: getInitialProps doesn't not run on Higher order component on page redirect using LINK or Button

I Got following piece of code on my higher order component (AuthLayout).This function works fine on page reload but when i redirect from one Link to another it seems not working and it loses all the existing context.
please help me to find out what i did wrong here?
I am using Nextjs Version 12.2.5
Thanks in Advance.
static async getInitialProps(context) {
try {
const token = await getFirebaseCookie('id_token', context);
const isLoggedIn = token ? true : false;
return {
isLoggedIn,
token
};
} catch (error) {
console.log(error)
}
}
Update:
my getFirebaseCookie function looks like this.
const getFirebaseCookie = (key, context = false) => {
// get cookie from __session using getCookie function
// parse the data from cookie
// get the relatedData using the key
try {
const cookieData = getCookie(FIREBASE_COOKIE, context);//client and server both
const data = cookieData ? cookieData: {};
if (data && data.hasOwnProperty(key)) {
return data[key];
} else {
console.log("not found")
}
} catch (error) {
console.log(error, 'getFirebaseCookie');
}
};
See this article: https://blog.logrocket.com/getinitialprops-vs-getserversideprops-nextjs/
getInitialProps is considered legacy; try using getServerSideProps instead and see how it works. I think it boils down to how they work on page transitions: they both fetch data on the server on the initial page load, but on page transitions (with next/link), getInitialProps runs on the client, so if an API is inaccessible, or at least behaves differently, on the client, it will not work the way you intend.

Redirect after logging in with $auth in nuxtjs

I'm having trouble redirecting my user when logging in with nuxt's default $auth configuration. Here's my problem:
Whenever I log in using the laravel/jwt provider, it redirects to my website home.
I have several points on the site where I need to open a modal with my login and I need to keep the user logged in on the same page he is on.
But I already tried to follow the documentation using the fake redirect flag and still I couldn't.
Is there any way to log in, if he is not on a specific page, such as the login page, he just refreshes instead of redirecting to the / route?
My usage:
async login() {
try {
this.loading(true)
await this.$auth.loginWith('laravelJWT', { data: this.form })
if (!this.redirectHome) {
this.$router.back()
this.$emit('is-logged')
}
} catch (error) {
this.loginError = true
} finally {
this.loading(false)
}
},
My resolution:
async login() {
await this.$auth
.loginWith('laravelJWT', { data: this.form })
.then(() => {
this.loading(true)
if (this.$route.name !== 'login') {
this.$router.go(this.$router.currentRoute)
}
this.$emit('is-logged')
})
.catch(() => {
this.loginError = true
})
.finally(() => {
this.loading(false)
})
},
use this.$auth.options.redirect = false before loginWith it will disable redirect.
when the promise resolved then you can call other api to refresh data or do whatever you want.

logout function refreshes the page but it's still logged in

I am following a course on Udemy, the instructor's side is using Angular 2 and I am trying to build the app using the latest version. The main problem I have, is that the logout function is accessed but because I have to refresh the page to display the login form again, for some reason, after the refresh, I see the login form but then it goes back to the part where I'm logged in.
Logout method on the back-end side:
#RequestMapping(value="/loggedOut", method=RequestMethod.POST)
public ResponseEntity logout(){
SecurityContextHolder.clearContext();
return new ResponseEntity("Logout Successfully!", HttpStatus.OK);
}
Logout function from my login service:
logOut() {
const url = 'http://localhost:8181/loggedOut';
const basicHeader = 'Basic ' + localStorage.getItem('credentials');
const headers = new HttpHeaders({
'x-auth-token' : JSON.stringify(localStorage.getItem('xAuthToken')),
'Authorization' : basicHeader
});
return this.http.post(url, '', { headers, responseType: 'text'});
The button responsible for logging out:
logout() {
this.loginService.logOut().subscribe(
res => {
location.reload();
console.log("Logged out")
},
error => {
console.log(error)
}
);
Technically, it goes as follow: Logged in -> Login form -> Logged in
Logged in:
Log in form:
If I remove the reload method, I can see that the logout method is accessed and I get a 200 from the back-end.
Network tab before refreshing:
The server response before refreshing:
Try clearing out your localStorage when logging out:
localStorage.clear();
Basically, this removes any trace that the app left when logging in.
**Try This Approach **
logout() {
this.loginService.logOut().subscribe(
res => {
if(res) {
// clear localStorage
localStorage.clear();
//navigate to login component
this.router.navigate(['loginPagePathName']);
console.log("Logged out")
}
},
error => console.log(error));
}
We don't need to refresh the page
Note :- You can also clear the local storage whenever login component load into the browser simply put localStorage.clear() inside ngOnInit method of loginComponent

How to detect the user's firebase authentication login status in a vue js project?

I am trying to detect the userstate. If the user is logged in I want to set the data "userstate" to true. I am using vuefire and firebase into my vue project. I tried the way shown below, but it does not work
data() {
return {
userstate:false
};
},
watch:{
userstate:{
firebase.auth().onAuthStateChanged(function(user){
if(user){
this.userstate= true;}
else{
this.userstate=false;
}
})}
In Firebase you can check whether the user is signed in or not by using a function provided by the firebase which is auth().currentUser
// user will return true which means user EXISTS!
let user = firebase.auth().currentUser;
if (user) {
this.userstate = true; // If it exists
} else {
this.userstate = false; // If it doesn't
}
There are cases when the above mentioned method returns null / undefined for the user. So this solution is for your existing solution. So in that case try modifying your existing function to this:
async function IsLoggedIn() {
try {
await new Promise((resolve, reject) =>
firbase.auth().onAuthStateChanged(
user => {
if (user) {
// Yes User is signed in.
resolve('User is there');
} else {
// No user is not signed in.
reject('There is no user');
}
},
// Prevent console errors
error => reject(error)
)
)
return true
} catch (error) {
return false
}
}
Also since you intend to watch for the auth state change you can simply register the listener right after you initialize Firebase, you do not necessarily have to insert it in a VueJS watch block, you can insert it in your main.js for example, and if you are using a store like VueX you can update the state in the store and pull that information from any component of the VueX application.
firebase.initializeApp(configOptions);
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.userstate = true;
} else {
this.userstate = false;
}
});

Redirect using Vue Router in Nuxt JS vuex

I'm building a login/register system as part of an app. I'm using Firebase and Vuex to handle authentication and database information. I have some actions in Nuxt JS that create the user, sign them in and log them out.
I'm trying to implement a redirect after the user has been successfully registered / when they click login, my code is:
export const actions = {
/*
* Create a user
*/
createUser ({commit}, payload) {
this.$fireAuth.createUserWithEmailAndPassword(payload.email, payload.password).then(function(firebaseUser) {
commit('setUser', payload)
}).catch(function(error) {
console.log('error logging in' + error)
});
},
/*
* Log a user into Beacon
*/
login ({commit}, payload) {
this.$fireAuth.signInWithEmailAndPassword(payload.email, payload.password).then(function(firebaseUser) {
commit('setUser', payload)
}).catch(function(error) {
console.log('error logging in' + error)
});
},
/*
* Sign a user out of Beacon
*/
signOut ({commit}) {
this.$fireAuth.signOut().then(() => {
commit('setUser', null)
}).catch(err => console.log(error))
}
}
I'm using Nuxt JS 2.9.2, on Vue JS 2.6.10
I have a few modules.
I've tried using this.router.push('/') and window.location.href, but would like to retain the SPA functionality.
You have two ways to do it:
$nuxt.$router.push in actions
Pass this.$router.push as argument in your action, and call where you need.
Hope this helps.

Categories

Resources