I am beginning to code with react native and I am trying my first app. I am in the process of making the login/signup of the app. I managed to log the user in but I cannot seem to figure out how to keep the user logged in when I close the app. How can I keep a user logged in to the app even when the app is closed?
This is what I have-
login.js
import { StatusBar } from 'expo-status-bar'
import { StyleSheet, Text, View, FlatList, Image, Button, Pressable, ScrollView } from 'react-native';
import React, {useState, useEffect} from 'react'
import { TextInput } from 'react-native-gesture-handler';
export default function Login(props) {
const message = props.navigation.getParam('message', null)
const [ username, setUsername ] = useState("")
const [ password, setPassword ] = useState("")
const log = () => {
fetch(`http://192.168.5.223:8000/home/login/`, {
method: 'POST',
headers: {
"Content-Type": 'application/json'
},
body: JSON.stringify({ username: username, password: password}),
})
.then( res => res.json())
.then( res => {
console.log(res)
if (res.valid === true){
if (res.set === true){
props.navigation.navigate("Home", {"user": username})
} else {
props.navigation.navigate("Profile", {"user": username})
}
} else {
props.navigation.navigate("Login", {'message': "username/password are incorrect"})
}
})
.catch( error => console.log(error))
}
const sign = () => {
props.navigation.navigate("Signup")
}
return (
<View style={styles.container}>
<ScrollView style={styles.scroll} >
<View style={styles.main}>
<Text style={styles.error}>{message}</Text>
<Text style={styles.label}>
Username:
</Text>
<TextInput style={styles.input} placeholder="Username"
onChangeText={ text => setUsername(text)} value={username}
autoCapitalize={'none'}
/>
<Text style={styles.label}>Password:</Text>
<TextInput style={styles.input} placeholder="Password" onChangeText={ text => setPassword(text)}
value={password} secureTextEntry={true} autoCapitalize={'none'}
/>
<Button onPress={ () => log()} title="Login"></Button>
</View>
</ScrollView>
<View style={styles.footer}>
<Button onPress={ () => sign()} title="Don't have an acount? Sign up now" />
</View>
<StatusBar style="auto"/>
</View>
)
}
Login.navigationOptions = screenProps => ({
headerLeft: () => null,
gestureEnabled: false,
headerStyle: {
backgroundColor: 'black'
},
headerTintColor: 'white',
})
CodePudding user response:
If you want your a user session to be persisted when the user closes and reopens the app you can use the AsyncStorage API.
See for instance this question Persistent User Session on React Native App
You need to store a token/cookie that will be used by your server to authenticate the user.