Published on

Fetch data from API using React Native Axios and store it in local DB

Authors
  • avatar
    Name
    James Williams
    Twitter
    About

Fetching Data from APIs and Storing it Locally in React Native

This article will guide you through the process of fetching data from an API using React Native's Axios library and storing it in a local database using AsyncStorage. This approach is particularly useful for applications that require offline access to data or need to improve performance by caching API responses.

Setting up the Project

  1. Install Axios:

    npm install axios
    
  2. Install AsyncStorage: AsyncStorage is already included in React Native.

Fetching Data with Axios

  1. Import Axios:

    import axios from 'axios';
    
  2. Define an API Endpoint:

    const apiEndpoint = 'https://api.example.com/data';
    
  3. Fetch Data:

    const fetchData = async () => {
      try {
        const response = await axios.get(apiEndpoint);
        return response.data;
      } catch (error) {
        console.error('Error fetching data:', error);
        return null;
      }
    };
    

Storing Data in AsyncStorage

  1. Import AsyncStorage:

    import AsyncStorage from '@react-native-async-storage/async-storage';
    
  2. Store Data:

    const storeData = async (data) => {
      try {
        await AsyncStorage.setItem('data', JSON.stringify(data));
      } catch (error) {
        console.error('Error storing data:', error);
      }
    };
    

Retrieving Data from AsyncStorage

  1. Retrieve Data:
    const retrieveData = async () => {
      try {
        const data = await AsyncStorage.getItem('data');
        return data ? JSON.parse(data) : null;
      } catch (error) {
        console.error('Error retrieving data:', error);
        return null;
      }
    };
    

Integrating Fetching and Storage

  1. Combine Fetching and Storage:

    const getData = async () => {
      const storedData = await retrieveData();
      if (storedData) {
        return storedData;
      } else {
        const fetchedData = await fetchData();
        if (fetchedData) {
          await storeData(fetchedData);
          return fetchedData;
        }
      }
      return null;
    };
    
  2. Use the getData Function:

    const [data, setData] = useState(null);
    
    useEffect(() => {
      const fetchDataAndStore = async () => {
        const fetchedData = await getData();
        setData(fetchedData);
      };
      fetchDataAndStore();
    }, []);
    

Handling Data Updates

  1. Update Data in AsyncStorage:

    const updateData = async (newData) => {
      try {
        await AsyncStorage.setItem('data', JSON.stringify(newData));
        setData(newData);
      } catch (error) {
        console.error('Error updating data:', error);
      }
    };
    
  2. Trigger Update on API Changes:

    useEffect(() => {
      // Logic to detect API changes (e.g., using a WebSocket)
      // ...
      updateData(newData);
    }, []);
    

Considerations

  • Data Expiration: Implement a mechanism to expire cached data after a certain time to ensure freshness.
  • Data Size: AsyncStorage has a limited storage capacity. Consider using a more robust database solution for larger datasets.
  • Data Security: If sensitive data is being stored, consider encryption techniques to protect it.

This comprehensive guide provides a solid foundation for fetching data from APIs and storing it locally in React Native. By leveraging Axios and AsyncStorage, you can enhance your application's offline capabilities and improve performance. Remember to adapt these techniques to your specific needs and consider the best practices for data management.