setItemAsync
- React Native course
- Advanced
- Lesson 38/83
- 5 min
Learn secure writes with setItemAsync.
setItemAsync
To write a value to the secure store you use SecureStore.setItemAsync. The function takes two parameters: key and value. Both must be strings. The function is asynchronous so it is awaited.
Example: await SecureStore.setItemAsync('token', 'abc123'). This writes the value 'abc123' with the key 'token' to the secure store. If you write again with the same key the old value is overwritten. If the value is a number or object you first convert it to a string with String() or JSON.stringify. Keys must be app-specific; meaningful names are chosen to prevent collisions.
Key and value
The first parameter of setItemAsync is the key, the second is the value. The key is the name used to access the value later; it must be unique in an app. The value is the string you want to store. Both must be strings.
When choosing a key you use app-specific names: 'token', 'user_id', 'refresh_token'. These names are later used to read the value with getItemAsync. If you use the same key twice the second write overwrites the first. The key length is limited; very long names are avoided. To store a number as the value you convert it with String(42).
Practice Write a token
Complete the saveToken function. It takes token as a parameter. Call await SecureStore.setItemAsync('token', token).
Starter code
import * as SecureStore from 'expo-secure-store';
export async function saveToken(token) {
// write the token to the secure store
}Sample solution
await SecureStore.setItemAsync('token', token);Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the write function
await SecureStore.____('token', 'abc123');
await SecureStore.setItemAsync('token', 'abc123');
Explanation: setItemAsync writes to the secure store.
2 What is the second parameter of setItemAsync?
await SecureStore.setItemAsync('token', ???)- Key
- Duration
- Permission
- Value Correct answer
Explanation: The second parameter is the value.
3 Match each field to its purpose
| Term | Meaning |
|---|---|
key |
Access name for value |
value |
Stored string |
string |
Required type |
await |
Async wait |