Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 142562

How can I make a function run every time I enter the component, using the useState?

$
0
0

I want the function that detects if there is a saved token to be verified, every time the component called login is executed.In login I have a function that verifies if a token exists, and if it exists automatically redirects to thehome view, otherwise it will remain in the login view.

Login

const Login = props => {
   const [loading, setLoading] = useState(true); 

   useEffect(() => {
    getTokenPrevious();
   }, [loading]);


    const getTokenPrevious = () => {
    AsyncStorage.multiGet(["token"])
        .then(value => {
            let token = value[0][1];

            if (token !== null) {
                props.navigation.navigate("home");
            } else {
                setLoading(false);
            }
        })
        .catch(error => {
            setLoading(false);
        });
   };


   if (loading) {
        return (
            <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
                <Text>Loading...</Text>
                <Spinner color={STYLES.bgHeader.backgroundColor} />
            </View>
        );
    }

  return (
    rest code login....

Sometimes when from the home view I use thebackbutton of the cell phone or when I try to tap on the logout button, this redirects me to thelogin view but this part is shown:

        return (
            <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
                <Text>Loading...</Text>
                <Spinner color={STYLES.bgHeader.backgroundColor} />
            </View>
        );

the part that should be shown is this:

  return (
    rest code login....

because the token no longer exists because it was deleted.

home

const Home= props => {

 clearStorage = () => {
 AsyncStorage.removeItem("token")
  .then(() => {
    props.navigation.navigate("Login");
  })

 };

 return (
 <View>
  <Button onPress={clearStorage()} ><Text>Logout</Text></Button>
 <View>
 )
}

How can i fix this?


Viewing all articles
Browse latest Browse all 142562

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>