I am trying to use React Native Async Storage to store user and auth values for a login feature.
Expo Snack of the code in question
The storeUser() function seems to work fine.
// Function to store username in async storage
const storeUser = async (value) => {
try {
await AsyncStorage.setItem('username', value);
// Successfully logs UserName
console.log('User added to async storage: ' + value);
} catch (e) {
// saving error
console.log('There was an error storing the username');
}
};
I am able to get the response and access the stored value from within the async functions, but returning the value doesn't make it available outside of the async function.
// Get username from local async storage
const getUser = async () => {
try {
const value = await AsyncStorage.getItem('username');
if (value !== null) {
//value previously stored - Logs UserName
console.log('Value being returned from getUser function: ' + value);
return value;
}
} catch (error) {
//error reading value
console.log('Could not get user');
}
};
Currently I am trying to assign the response to the user variable, but it returns a promise object instead of the response.
// Attempting to retrieve user from async storage and assign to a variable
const user = getUser().then((res) => {
if (res !== null) {
// Logs UserName
console.log('getUser function called, found user: ' + res);
return res;
} else console.log('There was an error with the getUser function.');
});
I've also tried awaiting the function and assigning that to a variable, but as far as I can tell that isn't allowed outside of an async function.
//Not valid because it is outside of an async function
//const user = await getUser()
I'm pretty sure something is fundamentally wrong how I am handling async/await here. How can I make the stored variable accessible outside of an async function?
You probably need to provide more information to allow anyone to understand the nature of your bug, but I'm guessing your application needs to handle the asynchronous parts differently. The Javascript appears correct, which makes me think the problem is the way you have structured your React code.
I'll go out a limb here and guess you are missing a useEffect
call that handles the setting/getting the value for that key into/out of AsyncStorage, and updates state accordingly. Your App()
component should have a useState
call to get a setter function for the username state and a useEffect
call to deal with the side effects of interacting with Async Storage. Something like this:
const App = () => {
const [username, setUsername] = useState();
useEffect(() => {
(async () => {
const user = await getUser()
setUsername(user);
})()
}, [setUsername]);
}
Without this basic framework, your React application is not going to know it needs to update any values returned from asynchronous operations.