2
votes

with a fetch, I'm getting a JWT from the server. This JWT is received, because when I do console.log(resData.token), the token is displayed in the console. But I can't save the token in the asyncstorage. The response is this:

{"_40": 0, "_55": null, "_65": 0, "_72": null}

I think the fetch is not done yet when the asynstorage.setItem runs, but how can I wait for it to finish first?

import React, { useState } from 'react';
import { Text, TextInput, Button, SafeAreaView } from 'react-native';

import AsyncStorage from '@react-native-community/async-storage';

const SignInScreen = props => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const SignInHandler = async () => {    
    const req = await fetch('http://localhost:8080/auth/signin', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({username: username, password: password})
    });
    const res = await req;
    if (res.ok) {
      const resData = await res.json();
      console.log(resData.token); // this works!
      await AsyncStorage.setItem('token', JSON.stringify(resData.token));
      console.log(AsyncStorage.getItem('token')); // this does not work
    } else {
      console.log('no user found');
    };
  };
  return (
    <SafeAreaView>
      <Text>Username</Text>
      <TextInput value={username} onChangeText={username => setUsername(username)} />
      <Text>Password</Text>
      <TextInput value={password} onChangeText={password => setPassword(password)} />
      <Button title="Sign In" onPress={SignInHandler} />    
    </SafeAreaView>
  );
};

SignInScreen.navigationOptions = navigation => ({
  headerShown: false
});

export default SignInScreen;
2

2 Answers

4
votes

The methods in AsyncStorage are asynchronous. You can use it like that:

console.log(await AsyncStorage.getItem('token'));

You can find more infos here in the doc

0
votes

{"_40": 0, "_55": null, "_65": 0, "_72": null}

This means the promise is not resolved. Async storage return the value in promise which we have to resolve.

Try using async - await function to resolve this issue.

await AsyncStorage.setItem('token', JSON.stringify(resData.token)); console.log(await AsyncStorage.getItem('token'));

This will resolve the issue