React Native: How to check login status? - react-native

I am using react native router flex for navigation and I have 2 scene A and B,also using redux for storing state.
if user login status is true the app will redirect to Page B else Page A.
But I am unable to check the status.componentDidMount always getting false state.
Page A:
componentDidMount () {
if(status)
{
Actions.b();
}
}
const mapStateToProps = ({userData}) => {
const {
status,
} = userData;
return {
status,
};
}
Let me know how to check login status.

Try to use componentWillReceiveProps. As soon as your status changes, your component will route to the next screen.
componentWillReceiveProps(nextProps) {
if(nextProps.status) {
Actions.b();
}
}

Related

React Native Navigation Not working after async storage get Item

const AuthLoadingScreen = ({ navigation }) => {
// auth init function
const _bootstrapAsync = async () => {
// Fetch token from storage
const session = await AsyncStorage.getItem('#todo-graphql:session');
// If session exists, validate it, else redirect to login screen
if (session) {
const sessionObj = JSON.parse(session);
var currentTime = Math.floor(new Date().getTime() / 1000);
if (currentTime < sessionObj.exp) {
setLogout(() => navigation.navigate('Auth'));
navigation.navigate('Main');
} else {
console.log("expired")
navigation.navigate('Auth');
}
} else {
navigation.navigate('Auth');
}
};
React.useEffect(() => {
console.log("inside Loading screen useeffect")
_bootstrapAsync();
}, []);
return (
<View>
<CenterSpinner />
</View>
);
}
export default AuthLoadingScreen;
I want to navigate to the main screen after checking the asyncstorage for the access token. If the access token is not expired. If the token is expired or no token exists the Auth screen will be shown. However, when I log in using the correct access token I am not navigated instead I have to refresh the expo go app and then it works.
You have to use a state to re-render the component.
Define a state like
const [loggedIn,setLogged] = useState(false);
Pass it as a dependency in useEffect so that the screen gets re-render.
To make it more efficient use redux state.

How do I set a fallback path/route with vueRouter if the navigation goBack ( < ) takes the user out of myb page?

I'm quite new with Vue, and vue-router. Right now I'm working on a page where we organize tennis matches, I have this component called goBack, it basically checks your browser history entries and take you back to the previous one, similar to the back-arrow in your browser. So I have this behavior which I don't like, and I don't know how to change it => if I set match, pass you the URL, if you enter and click on my goBack Comp it will take you out of my page. I want to avoid that with this logic, if your last browser history entry is not inside my page I want to redirect you to my home.
Here's the goBack component code:
setup(props, { attrs }) {
const router = useRouter()
const { t } = useI18n()
const goBack = (): void => {
if (attrs.onClick) return
if (router.options.history.state.back === null) {
router.replace('/')
} else {
router.back()
}
}
return {
t,
goBack
}
}
})
</script>
Thank you!

React Native component not making new query after mount

We're using react-native-web so native and web are in one code base. I have an instance where a user clicks the back button to return to a main page and this should fire a re-query of the backend. We're also using Apollo hooks for queries, useQuery
So far, this works for web but not for native. I tried creating a useEffect hook to check if navigation and specifically navigation.isFocused() like so:
const {
data,
loading: childProfilesLoading,
error: childProfilesError,
refetch: refetchChildProfiles,
} = useQuery(LIST_PROFILES, {
fetchPolicy: 'no-cache',
})
// this method also exists on the previous page
const goBack = () => {
if (history) {
history.goBack()
} else if (navigation) {
navigation.goBack()
}
}
useEffect(() => {
if (navigation?.isFocused()) {
refetchChildProfiles()
}
}, [navigation, refetchChildProfiles])
but this doesn't work. Is there something I'm missing in forcing a refetch on native?

How to save history of component in react native using react native router flux

I am using react native router flux in android project for routing when i jump from one component to another than the history of last component is remove from stack i want to store components history please anyone.
instead of jump you can use
Action.keynameofyournextpage()
ex to go to page1 to page2
can use
Actions.page2()
in page 1
If you want to save a record of the components, use the AsyncStorage module to save them.
Example
import {AsyncStorage} from 'react-native';
//set data
_storeData = async () => {
try {
await AsyncStorage.setItem('componenthistory', componenthistory);
} catch (error) {
// Error saving data
}
};
...
//get data
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('componenthistory');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};

How to set dashboard as first screen after login in react-native

I am using react-native where my first screen is Welcome screen and I want to set dashboard on my first screen when the user is login.
Here is my code:
componentWillMount(){
var self = this;
AsyncStorage.getItem(AppStrings.contracts.IS_LOGGED_IN).then((json) =>{
try{
var userDetail = JSON.parse(json);
if(userDetail.isLoggedIn != undefined && userDetail.isLoggedIn == true){
Actions.dashboard();
}
}catch(e){
}
})
}
I set this code on the Welcome screen and its working fine in IOS. But in android issue is it shows the Welcome screen for 5 to 10 seconds before going to dashboard screen when the user is login.
Here I am using react-native-router-flux for the navigation bar.
Because AsyncStorage.getItem() is asynchronous, your render() function is being called BEFORE it has been fulfilled.
So the flow of your application is:
Call componentWillMount()
AsyncStorage.getItem()
render() - This is where you see your Welcome Screen for 5-10 seconds
AsyncStorage has been fulfilled - .then() and then the User gets redirected to the dashboard.
I would set an isLoaded flag in your state:
constructor() {
super();
this.state = {
isLoaded: false,
}
}
Then inside of your componentWillMount() function, set the value to true once AsyncStorage has fulfilled its Promise.
try {
var userDetail = JSON.parse(json);
if(userDetail.isLoggedIn != undefined && userDetail.isLoggedIn == true){
Actions.dashboard();
}
this.setState({ isLoaded: true });
}
And finally, I would add some sort of loading indicator inside of render() to show the User that your application is still performing some logic.
render() {
if(this.state.isLoading) {
return <Text>I am loading</Text>
} else {
return ...
}
}