|
| 1 | +import type { FC } from "react"; |
| 2 | +import { useState } from "react"; |
| 3 | +import { createAsyncStorage } from "@react-native-async-storage/async-storage"; |
| 4 | +import React from "react"; |
| 5 | + |
| 6 | +const STORAGE_KEY = "testing"; |
| 7 | + |
| 8 | +const BasicCrud: FC = () => { |
| 9 | + const [storedNumber, setStoredNumber] = useState<number | null>(null); |
| 10 | + const [storage] = useState(() => createAsyncStorage("test-web")); |
| 11 | + |
| 12 | + function reportError(e: unknown) { |
| 13 | + alert(JSON.stringify(e, null, 2)); |
| 14 | + } |
| 15 | + |
| 16 | + async function readCurrent() { |
| 17 | + try { |
| 18 | + const value = await storage.getItem(STORAGE_KEY); |
| 19 | + setStoredNumber(value ? Number(value) : null); |
| 20 | + } catch (e: any) { |
| 21 | + reportError(e); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + const increaseByTen = async () => { |
| 26 | + const newNumber = (storedNumber ?? 0) + 10; |
| 27 | + |
| 28 | + try { |
| 29 | + await storage.setItem(STORAGE_KEY, `${newNumber}`); |
| 30 | + setStoredNumber(newNumber); |
| 31 | + await readCurrent(); |
| 32 | + } catch (e) { |
| 33 | + reportError(e); |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + const removeItem = async () => { |
| 38 | + await storage.removeItem(STORAGE_KEY).catch(reportError); |
| 39 | + await readCurrent(); |
| 40 | + }; |
| 41 | + |
| 42 | + const listAllKeys = async () => { |
| 43 | + try { |
| 44 | + const keys = await storage.getAllKeys(); |
| 45 | + alert("keys: " + keys.join(", ")); |
| 46 | + } catch (e) { |
| 47 | + reportError(e); |
| 48 | + } |
| 49 | + }; |
| 50 | + |
| 51 | + React.useEffect(() => { |
| 52 | + readCurrent(); |
| 53 | + }, [storage]); |
| 54 | + |
| 55 | + return ( |
| 56 | + <div> |
| 57 | + <p>Currently stored: </p> |
| 58 | + <p>{storedNumber}</p> |
| 59 | + <button onClick={increaseByTen}> Increase by 10</button> |
| 60 | + <button onClick={removeItem}>remove item</button> |
| 61 | + <button onClick={listAllKeys}>list all keys</button> |
| 62 | + </div> |
| 63 | + ); |
| 64 | +}; |
| 65 | + |
| 66 | +export default BasicCrud; |
0 commit comments