0

Working with React-Native project, I decided to write small service for AsyncStorage which allows to work with objects, based on official docs

    import {AsyncStorage} from "react-native-web";


        export async function getUserFromStore() {
            try {
                const user = await AsyncStorage.getItem('userData');

                return  JSON.parse(user);
            } catch (error) {
                console.log('ERROR. Trying to get user data to store, got  ', error)
            }
        } 

export async function saveUserToStore(data) {
    await AsyncStorage.setItem(
        'userData',
        JSON.stringify(data),
        (error) => {
            console.log('ERROR. Trying to set user data to store, got ', error)
        }
    );
}

I'm setting user data object during login. An I'm getting in main component in order to decide what to render

const AppStackScreen = () => (
        <AppStack.Navigator>
            <AppStack.Screen name="Tabbed" component={TabsScreenNavigationScreen} />
        </AppStack.Navigator>
    );

export default () => {
    const user = AsyncStoreService.getUserFromStore();

    console.log('GOT USER', user)
    return (
        <NavigationContainer>
            {user ?
                <AppStackScreen/>
                :
                <AuthStackNavigationScreen/>
            }
        </NavigationContainer>
    )
};

So I need to get object like {name: 'John', mail: 'john@mail.loc}, but instead of this I get Promise{[[PromiseStatus: 'resolved']], [[PromiseValue: {name: 'John', mail: 'john@mail.loc}]]} Why it happens and why I dont get object with user params

Sam Fisher
  • 746
  • 2
  • 10
  • 27
  • 3
    An `async` function always returns a promise. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Syntax – Felix Kling Jun 18 '20 at 11:52
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith Jun 18 '20 at 12:03
  • 1
    You will need a fair bit more than just an await here. Your code should handle what JSX to return when there is no data yet as well as what state to update once the data has arrived (so that the updated JSX is returned based on the updated state). – crashmstr Jun 18 '20 at 12:03

1 Answers1

5

The function getUserFromStore is async and the return value of an async function is a Promise. You need to resolve that promise to get the value.