Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncStorage.setItem returns null (await fetch to finish)

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;
like image 343
Sam Leurs Avatar asked Dec 05 '25 03:12

Sam Leurs


1 Answers

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

like image 131
Poptocrack Avatar answered Dec 07 '25 20:12

Poptocrack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!