Created
February 1, 2020 16:55
-
-
Save markmssd/40c36bb6d5ec6567175e679f12d02a1a to your computer and use it in GitHub Desktop.
Helper hook for @react-native-community/async-storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react' | |
import AsyncStorage from '@react-native-community/async-storage' | |
export const useAsyncStorage = <T>(key: string, initialValue: T) => { | |
const [storageItem, setStorageItem] = useState<T>(initialValue) | |
// initialize | |
useEffect(() => { | |
AsyncStorage.getItem(key) | |
.then((value) => { | |
if (value !== null) { | |
try { | |
const parsed = JSON.parse(value) | |
setStorageItem(parsed) | |
return parsed | |
} catch (e) { | |
setStorageItem(value) | |
return value | |
} | |
} else { | |
return updateStorageItem(initialValue) | |
} | |
}) | |
}, []) | |
const updateStorageItem = (data: T): Promise<T> => { | |
if (typeof data === 'string') { | |
return AsyncStorage.setItem(key, data) | |
.then(() => setStorageItem(data)) | |
.then(() => data) | |
} else { | |
try { | |
const stringified = JSON.stringify(data) | |
return AsyncStorage.setItem(key, stringified) | |
.then(() => setStorageItem(data)) | |
.then(() => data) | |
} catch (e) { | |
setStorageItem(data) | |
return Promise.resolve(data) | |
} | |
} | |
} | |
return [storageItem, updateStorageItem] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment