Sherlock / components / storage.tsx
storage.tsx
Raw
import AsyncStorage from '@react-native-async-storage/async-storage';

/**
 * Stores key-value pair
 * @param key string
 * @param value string
 */
export const storeData = async (key: string, value: any) => {
    try {
        await AsyncStorage.setItem(key, JSON.stringify(value));
    } catch (e) {
        console.error("Error storing data: ",e);
        // throw e;
    }
};

/**
 * Retrieves stored value
 * @param key string
 * @returns string
 */
export const getData = async (key: string) => {
    try {
        const value = await AsyncStorage.getItem(key);
        if (value !== null) {
            return JSON.parse(value);
        }
    } catch (e) {
        console.error("Error getting data: ",e);
        // throw e;
        return null;
    }
};

/**
 * Stores JSON object
 * @param key string
 * @param value JSON object
 */
export const storeObject = async (key:string, value:{}) =>{
    try{
        const jsonValue = JSON.stringify(value)
        await AsyncStorage.setItem(key, jsonValue)
    } catch(e){
        console.error('Error storing object: '+key+":", e)
    }
};

/**
 * 
 * @param key 
 * @returns JSON object
 */
export const getObject = async(key:string)=>{
    try{
        const jsonValue = await AsyncStorage.getItem(key);
        return jsonValue != null ? JSON.parse(jsonValue) :null;
    } catch(e){
        console.error("Error retrieving objext from store:", e)
        return null;
    }
};