Skip to content

Instantly share code, notes, and snippets.

@markmssd
Created February 1, 2020 16:55
Show Gist options
  • Save markmssd/40c36bb6d5ec6567175e679f12d02a1a to your computer and use it in GitHub Desktop.
Save markmssd/40c36bb6d5ec6567175e679f12d02a1a to your computer and use it in GitHub Desktop.
Helper hook for @react-native-community/async-storage
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