getItemAsync
- React Native course
- Advanced
- Lesson 39/83
- 5 min
Learn secure reads with getItemAsync.
getItemAsync
To read a value from the secure store you use SecureStore.getItemAsync. The function takes one parameter: the key. If the key exists it returns the string value, otherwise it returns null. The function is asynchronous so it is awaited.
Example: const token = await SecureStore.getItemAsync('token'). This reads the value of the 'token' key. If the value does not exist token becomes null. So a null check after reading is a common pattern: if (token) { ... }. This is a safe way to check whether the user has logged in before.
Null check
getItemAsync returns null if the key does not exist. So a null check after reading is mandatory. The common pattern: const token = await SecureStore.getItemAsync('token'); if (!token) { return null; }. This allows early exit when the user has not logged in.
Without the null check, trying to use the token directly may raise an error; for example token.length raises a null error. So after each read an if (token) check is done. If the token is present it is added as an Authorization header to the API request: headers: { Authorization: `Bearer ${token}` }.
Practice Read the token and check
Complete the loadToken function. Call const token = await SecureStore.getItemAsync('token'). If !token, return null. Otherwise return token.
Starter code
import * as SecureStore from 'expo-secure-store';
export async function loadToken() {
// read the token, do a null check
}Sample solution
const token = await SecureStore.getItemAsync('token');
if (!token) return null;
return token;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the read function
const token = await SecureStore.____('token');
const token = await SecureStore.getItemAsync('token');
Explanation: getItemAsync reads from the secure store.
2 What does getItemAsync return when the key does not exist?
const value = await SecureStore.getItemAsync('missing')- null Correct answer
- Throws an error
- The string 'undefined'
- Empty string
Explanation: If the key does not exist it returns null.
3 Match each field to its purpose
| Term | Meaning |
|---|---|
key |
Read name |
value |
Returned string |
null |
When key absent |
await |
Async wait |