I have the following code which check the user_id if available and then log me in but it logs me in only if I refresh the app. Any idea how to make this happen without this?
This is the order of functions:
First when you click the login button from Login.js
:
<TouchableOpacity onPress={handleSubmit(_signIn)} style={{margin: 10, alignItems: 'center'}}>
then _signIn
function which is in Login.js
_signIn = (values, dispatch) => {
const email = values.email;
const password = values.password;
dispatch(loginUser(email, password));
}
Now we dispatched email and password to loginUser
from authActions.js
export function loginUser(email, password) {
return function (dispatch) {
return axios.post(SIGNIN_URL, { email, password }).then((response) => {
var { user_id, token } = response.data;
onSignIn(user_id); // Here I pass 'user_id' to onSignIn function
}).catch((error) => {
dispatch(addAlert("Could not log in."));
});
};
}
Now we get the user_id
from loginUser
inside Auth.js
import { AsyncStorage } from "react-native";
const USER_KEY = "auth_key";
export const onSignIn = (user_id) => AsyncStorage.setItem(USER_KEY, user_id);
export const onSignOut = () => AsyncStorage.removeItem(USER_KEY);
export const isSignedIn = () => {
return new Promise((resolve, reject) => {
AsyncStorage.getItem(USER_KEY)
.then(res => {
if (res !== null) {
resolve(true);
} else {
resolve(false);
}
})
.catch(err => reject(err));
});
};
Now in App.js
I am calling the function isSignedIn
to check if user_id
is available and if so will choose which screen to show
constructor(props) {
super(props);
this.state = {
signedIn: false,
checkedSignIn: false
};
}
componentDidMount() {
isSignedIn()
.then(res => this.setState({ signedIn: res, checkedSignIn: true }))
.catch(err => alert("An error occurred"));
}
render() {
const { checkedSignIn, signedIn } = this.state;
// If we haven't checked AsyncStorage yet, don't render anything (better ways to do this)
if (!checkedSignIn) {
return null;
}
const Layout = createRootNavigator(signedIn);