Skip to content

Instantly share code, notes, and snippets.

@syuraj
Created June 25, 2021 21:59
Show Gist options
  • Save syuraj/f622a65e73e7c825955165b0a5fb0af9 to your computer and use it in GitHub Desktop.
Save syuraj/f622a65e73e7c825955165b0a5fb0af9 to your computer and use it in GitHub Desktop.
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