Search code examples
functionreact-nativereturnasyncstorage

React Native - get data from return


in my App.js i want to return the Token and a RememberMe const from the AsyncStorage. The 'Get' function is in another file. I cant read the Data in the App.js from the function and i hope you can help me.

This is my code:

const.js

export const getToken = async () => {
    const Token = await AsyncStorage.getItem('IN_Token');
    const ReMe = await AsyncStorage.getItem('RememberMe');
    return (Token, ReMe);
}

App.js

export default () => {
    const [isLoading, setIsLoading] = React.useState(true);

    React.useEffect(() => {
        setTimeout(() => {
            setIsLoading(false);
        }, 3000)
        getToken()
    }, [])

    if (isLoading) {
        return <Splash/>
    }
    if (getToken) {
        return <HomeStack/>
    }

    return (

        <AuthStack/>
    )
}

Solution

  • First of all you should return a object :

    export const getToken = async () => {
        const Token = await AsyncStorage.getItem('IN_Token');
        const ReMe = await AsyncStorage.getItem('RememberMe');
        return {Token, ReMe};
    }
    

    Second getToken is a async function, it returns a promise you have to wait for it to resolve

    export default () => {
        const [isLoading, setIsLoading] = React.useState(true);
        const [tokenObj, setTokenObj] = React.useState({});
        React.useEffect(() => {
            getToken().then(res=> {
               setIsLoading(false);
               setTokenObj(res)
            })
        }, [])
    
        if (isLoading) {
            return <Splash/>
        }
        if (tokenObj.Token) {
            return <HomeStack/>
        }
    
        return (
    
            <AuthStack/>
        )
    }
    

    Try this