Created
June 25, 2021 21:59
-
-
Save syuraj/f622a65e73e7c825955165b0a5fb0af9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { Storage } from '@ionic/storage'; | |
const storage = new Storage(); | |
storage.create(); | |
export const useIonicStorage = (key, defaultValue) => { | |
const [value, setValue] = useState(defaultValue); | |
useEffect(() => { | |
(async function () { | |
const stored = await storage.get(key); | |
const initial = stored ? JSON.parse(stored) : defaultValue; | |
setValue(initial); | |
})(); | |
}, []); | |
useEffect(() => { | |
(async function () { | |
await storage.set(key, JSON.parse(value)); | |
})(); | |
}, [key, value]); | |
return [value, setValue]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment