Day 8: Storing Data Locally Using AsyncStorage


In this tutorial, you’ll learn how to store data locally in React Native using AsyncStorage. Local storage is useful for persisting data such as user preferences, login information, or app settings across different sessions. By the end of today’s tutorial, you’ll be able to store and retrieve data from local storage, providing a better user experience in your app.


What You Will Learn Today:

  1. Installing and setting up AsyncStorage
  2. Storing data locally using setItem
  3. Retrieving data from local storage using getItem
  4. Handling data deletion and clearing local storage
  5. Managing user input and displaying stored data

Step 1: Installing AsyncStorage

First, we need to install the AsyncStorage package, which allows us to read and write data to the device’s local storage.

  1. Open your terminal and run the following command to install AsyncStorage:
expo install @react-native-async-storage/async-storage

This will install the AsyncStorage package in your project.


Step 2: Storing Data Locally

Let’s start by storing user input locally using AsyncStorage. We’ll modify the HomeScreen to store the user’s name in local storage when they submit the form.

Modify HomeScreen.js as follows:

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 HomeScreen() {
  const [name, setName] = useState('');
  const [savedName, setSavedName] = useState('');

  const saveName = async () => {
    try {
      await AsyncStorage.setItem('user_name', name); // Save name in local storage
      setSavedName(name); // Update the state
      alert('Name saved locally!');
    } catch (error) {
      console.log(error);
    }
  };

  const loadName = async () => {
    try {
      const value = await AsyncStorage.getItem('user_name'); // Retrieve the name
      if (value !== null) {
        setSavedName(value); // Update state with the saved name
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Save Your Name Locally</Text>

      <TextInput
        style={styles.input}
        placeholder="Enter your name"
        value={name}
        onChangeText={setName}
      />

      <Button title="Save Name" onPress={saveName} />

      <Text style={styles.savedName}>Stored Name: {savedName}</Text>

      <Button title="Load Name" onPress={loadName} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 24,
    marginBottom: 20,
  },
  input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    width: '80%',
    paddingHorizontal: 10,
    marginBottom: 20,
  },
  savedName: {
    fontSize: 18,
    marginTop: 20,
    color: 'green',
  },
});

Explanation:

  • setItem: Stores the user’s name in local storage.
  • getItem: Retrieves the stored name from local storage.
  • When the user enters a name and clicks Save Name, it’s stored locally and displayed under Stored Name.
  • The Load Name button fetches the saved name from local storage.
See also  Optimizing Migrations for Large-Scale Applications in Laravel

Step 3: Retrieving Data from Local Storage

To retrieve data from AsyncStorage, we use the getItem method. In the example above, when the user clicks the Load Name button, the app fetches the stored name and displays it on the screen.

You can also automatically load data when the component mounts. Let’s modify the useEffect hook to load the stored name when the app starts.

Modify HomeScreen.js to include useEffect:

import React, { useState, useEffect } from 'react';
// Same imports as before

export default function HomeScreen() {
  const [name, setName] = useState('');
  const [savedName, setSavedName] = useState('');

  useEffect(() => {
    loadName(); // Load the stored name when the component mounts
  }, []);

  // Same saveName and loadName functions as before

  return (
    <View style={styles.container}>
      {/* Same UI elements as before */}
    </View>
  );
}

Explanation:

  • useEffect: When the component mounts, the app automatically calls the loadName function to retrieve and display any saved data.

Step 4: Deleting Data from Local Storage

There may be times when you need to delete data from local storage. You can use the removeItem method to remove a specific item from AsyncStorage.

Let’s add a Clear Name button to delete the saved name from storage.

Modify HomeScreen.js to include a new button and method for clearing the stored name:

const clearName = async () => {
  try {
    await AsyncStorage.removeItem('user_name'); // Remove the stored name
    setSavedName(''); // Clear the state
    alert('Name cleared from local storage!');
  } catch (error) {
    console.log(error);
  }
};

return (
  <View style={styles.container}>
    {/* Same UI elements as before */}

    <Button title="Clear Name" onPress={clearName} />
  </View>
);

Explanation:

  • removeItem: This method removes the specified key (user_name) from local storage.
  • After clearing the name from storage, we also reset the local state using setSavedName('').

Step 5: Clearing All Data from AsyncStorage

If you want to clear all data from AsyncStorage, you can use the clear method. This will remove everything stored in AsyncStorage, which can be useful for logging out users or resetting app data.

See also  Day 6: Securing Your API with HTTPS and Environment Variables

Let’s modify the example to clear all data when needed:

const clearAllData = async () => {
  try {
    await AsyncStorage.clear(); // Clear all local storage data
    setSavedName(''); // Reset state
    alert('All local storage data cleared!');
  } catch (error) {
    console.log(error);
  }
};

return (
  <View style={styles.container}>
    {/* Same UI elements as before */}

    <Button title="Clear All Data" onPress={clearAllData} />
  </View>
);

Explanation:

  • clear: This method clears all stored data from AsyncStorage. Be careful when using this, as it will remove all data, not just specific items.

Step 6: Storing More Complex Data

AsyncStorage can only store strings, but you can store more complex data types like objects and arrays by using JSON serialization.

For example, to store an object in AsyncStorage, you need to stringify it:

const saveUserDetails = async () => {
  const userDetails = { name: name, email: '[email protected]' };
  try {
    await AsyncStorage.setItem('user_details', JSON.stringify(userDetails)); // Convert object to string
    alert('User details saved locally!');
  } catch (error) {
    console.log(error);
  }
};

const loadUserDetails = async () => {
  try {
    const jsonValue = await AsyncStorage.getItem('user_details');
    if (jsonValue != null) {
      const userDetails = JSON.parse(jsonValue); // Convert string back to object
      console.log('Loaded user details:', userDetails);
    }
  } catch (error) {
    console.log(error);
  }
};

Explanation:

  • JSON.stringify(): Converts an object or array to a string before storing it in AsyncStorage.
  • JSON.parse(): Converts the stored string back into an object or array when retrieving it.

Step 7: Recap and Summary

Today, you learned how to store data locally using AsyncStorage in React Native. Here’s a quick summary of what you’ve done:

  • Installed and set up AsyncStorage in your app.
  • Stored simple data such as a user’s name in local storage.
  • Retrieved and displayed the stored data when the app starts.
  • Deleted specific data from local storage.
  • Cleared all local storage data when needed.
  • Stored and retrieved complex data structures like objects using JSON.
See also  Day 10: Optimizing and Deploying Your API

With AsyncStorage, you can now persist data across app sessions, providing a better user experience. This is useful for things like user settings, login states, and more!


Next Up: Day 9 – Adding Push Notifications

In Day 9, we’ll introduce push notifications using *Expo Notifications*. You’ll learn how to set up notifications, schedule them, and handle them inside your app.

Stay tuned for more exciting functionality tomorrow!


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.