0
0
React Nativemobile~20 mins

AsyncStorage for key-value in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Key-Value Storage
This screen lets users save a text value with a key and retrieve it later using AsyncStorage.
Target UI
┌───────────────────────────────┐
│ Simple Key-Value Storage       │
├───────────────────────────────┤
│ Key: [______________]          │
│ Value: [______________]        │
│                               │
│ [Save]    [Load]               │
│                               │
│ Stored Value:                  │
│                               │
│                               │
└───────────────────────────────┘
Two TextInput fields: one for key, one for value
A Save button that stores the value under the key using AsyncStorage
A Load button that retrieves the value for the entered key and shows it below
Show the loaded value or a message if no value found
Handle errors silently and keep UI simple
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function KeyValueStorage() {
  const [key, setKey] = useState('');
  const [value, setValue] = useState('');
  const [storedValue, setStoredValue] = useState('');

  // TODO: Add saveValue function

  // TODO: Add loadValue function

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Simple Key-Value Storage</Text>
      <Text>Key:</Text>
      <TextInput
        style={styles.input}
        value={key}
        onChangeText={setKey}
        placeholder="Enter key"
        accessibilityLabel="Key input"
      />
      <Text>Value:</Text>
      <TextInput
        style={styles.input}
        value={value}
        onChangeText={setValue}
        placeholder="Enter value"
        accessibilityLabel="Value input"
      />
      <View style={styles.buttonRow}>
        <Button title="Save" onPress={() => {}} accessibilityLabel="Save button" />
        <Button title="Load" onPress={() => {}} accessibilityLabel="Load button" />
      </View>
      <Text style={styles.storedValueLabel}>Stored Value:</Text>
      <Text style={styles.storedValue}>{storedValue}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 20,
    flex: 1,
    backgroundColor: '#fff'
  },
  title: {
    fontSize: 20,
    marginBottom: 10
  },
  input: {
    borderWidth: 1,
    borderColor: '#999',
    padding: 8,
    marginBottom: 10,
    borderRadius: 4
  },
  buttonRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 20
  },
  storedValueLabel: {
    fontWeight: 'bold',
    marginBottom: 4
  },
  storedValue: {
    fontSize: 16,
    color: '#333'
  }
});
Task 1
Task 2
Task 3
Task 4
Solution
React Native
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function KeyValueStorage() {
  const [key, setKey] = useState('');
  const [value, setValue] = useState('');
  const [storedValue, setStoredValue] = useState('');

  async function saveValue() {
    try {
      if (key) {
        await AsyncStorage.setItem(key, value);
        setStoredValue('Value saved successfully');
      } else {
        setStoredValue('Please enter a key');
      }
    } catch {
      setStoredValue('Error saving value');
    }
  }

  async function loadValue() {
    try {
      if (key) {
        const val = await AsyncStorage.getItem(key);
        if (val !== null) {
          setStoredValue(val);
        } else {
          setStoredValue('No value found for this key');
        }
      } else {
        setStoredValue('Please enter a key');
      }
    } catch {
      setStoredValue('Error loading value');
    }
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Simple Key-Value Storage</Text>
      <Text>Key:</Text>
      <TextInput
        style={styles.input}
        value={key}
        onChangeText={setKey}
        placeholder="Enter key"
        accessibilityLabel="Key input"
      />
      <Text>Value:</Text>
      <TextInput
        style={styles.input}
        value={value}
        onChangeText={setValue}
        placeholder="Enter value"
        accessibilityLabel="Value input"
      />
      <View style={styles.buttonRow}>
        <Button title="Save" onPress={saveValue} accessibilityLabel="Save button" />
        <Button title="Load" onPress={loadValue} accessibilityLabel="Load button" />
      </View>
      <Text style={styles.storedValueLabel}>Stored Value:</Text>
      <Text style={styles.storedValue}>{storedValue}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 20,
    flex: 1,
    backgroundColor: '#fff'
  },
  title: {
    fontSize: 20,
    marginBottom: 10
  },
  input: {
    borderWidth: 1,
    borderColor: '#999',
    padding: 8,
    marginBottom: 10,
    borderRadius: 4
  },
  buttonRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 20
  },
  storedValueLabel: {
    fontWeight: 'bold',
    marginBottom: 4
  },
  storedValue: {
    fontSize: 16,
    color: '#333'
  }
});

We added two async functions: saveValue and loadValue. saveValue stores the entered value under the entered key using AsyncStorage.setItem. It checks if the key is not empty and shows a success or error message. loadValue retrieves the stored value for the key using AsyncStorage.getItem. If found, it shows the value; if not, it shows a message that no value was found. Both functions handle errors silently by showing a simple error message. The Save and Load buttons call these functions when pressed. This creates a simple key-value storage screen that is easy to use and understand.

Final Result
Completed Screen
┌───────────────────────────────┐
│ Simple Key-Value Storage       │
├───────────────────────────────┤
│ Key: [username______]          │
│ Value: [john_doe_____]         │
│                               │
│ [Save]    [Load]               │
│                               │
│ Stored Value:                  │
│ john_doe                      │
│                               │
└───────────────────────────────┘
User types a key and value, then taps Save to store the value.
User types a key and taps Load to retrieve and display the stored value below.
If no value is found for the key, a message shows 'No value found for this key'.
If key is empty, a message prompts to enter a key.
Stretch Goal
Add a Clear button that removes the stored value for the entered key from AsyncStorage.
💡 Hint
Use AsyncStorage.removeItem(key) inside an async function triggered by the Clear button.