CodeBlanks Logo Icon CodeBlanks

getItem

Learn to read data with AsyncStorage.getItem.

Reading data with getItem

AsyncStorage.getItem is used to read a value from a key. It takes one parameter: the key (string). Since the operation is asynchronous you wait with await. The return value is the stored string; if the key does not exist null is returned.

const value = await AsyncStorage.getItem('theme');

In this example the value is read from the key 'theme'. If you have not previously written a value with setItem you get null. Therefore it is good practice to check for null before using the getItem result.

Null check

getItem returns null for a key that is not found. Checking for null before using the result prevents the app from crashing. The simplest way: write an if (value !== null) condition.

const value = await AsyncStorage.getItem('theme');
if (value !== null) {
  // use the value
}

Sometimes you may want to provide a default value: const theme = value ?? 'light'. Here the ?? operator uses the right side if the left side is null or undefined. This is an elegant way to handle missing data.

Practice Your turn: read a value with getItem

Read the value with AsyncStorage.getItem('theme') and assign it to a value variable. Use await. The function should be async.

Starter code

App.js
import AsyncStorage from '@react-native-async-storage/async-storage';

async function loadTheme() {
  // read the theme value
  return null;
}

Sample solution

App.js
import AsyncStorage from '@react-native-async-storage/async-storage';

async function loadTheme() {
  const value = await AsyncStorage.getItem('theme');
  return value;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match: method and return

Term Meaning
setItem writes value
getItem returns value
removeItem deletes value

2 What does getItem return for a missing key?

App.js
await AsyncStorage.getItem('missing')
  • Returns null Correct answer
  • Throws an error
  • Returns an empty string
  • Returns undefined

Explanation: getItem returns null for a missing key.

3 Fill in the blank: getItem call

Question
const value = await AsyncStorage.____('theme');
Answer
const value = await AsyncStorage.getItem('theme');

Explanation: You read a value with getItem.

All lessons in Beginner