Link state with browser.storage.local via useEffect

This commit is contained in:
Ceda EI 2020-09-09 15:24:55 +05:30
parent 919e948d82
commit 537deb944e
1 changed files with 63 additions and 5 deletions

View File

@ -1,15 +1,73 @@
/* global browser */ /* global browser */
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
function App() { function App() {
const [ advanced, setAdvanced ] = useState(false); const [ advanced, setAdvanced ] = useState(undefined);
const [ words, setWords ] = useState([]); const [ words, setWords ] = useState(undefined);
const [ word, setWord ] = useState(""); const [ word, setWord ] = useState("");
const [ regex, setRegex ] = useState(""); const [ regex, setRegex ] = useState(undefined);
const [ flags, setFlags ] = useState(""); const [ flags, setFlags ] = useState(undefined);
function removeWord(idx) { function removeWord(idx) {
setWords([...words.slice(0, idx), ...words.slice(idx+1)]); setWords([...words.slice(0, idx), ...words.slice(idx+1)]);
} }
/*
* Get inital state from storage.
*
* setterDefaultValue is key: [setter, defaultValue] object where each
* setter sets the state while the defaultValue is set if the value is
* undefined
*/
useEffect(() => {
const setterDefaultValue = {
advanced: [ setAdvanced, false ],
words: [ setWords, ["attendance", "roll number", "present"] ],
regex: [ setRegex, "" ],
flags: [ setFlags, "" ]
}
Object.keys(setterDefaultValue).forEach(key => {
const [ setter, defaultValue ] = setterDefaultValue[key];
browser.storage.local.get(key)
.then(value => {
if (key in value)
setter(value[key])
else {
browser.storage.local.set({ [key]: defaultValue });
setter(defaultValue);
}
})
.catch(() => {
browser.storage.local.set({ [key]: defaultValue });
setter(defaultValue);
});
});
}, []);
/* Sync state to storage
*
* For some reason browser.storage.local.set doesn't work unless I call it
* from the callback of browser.storage.local.get. Don't touch.
*/
useEffect(() => {
browser.storage.local.get("regex")
.then((() => regex !== undefined && browser.storage.local.set({ regex: regex })));
}, [regex]);
useEffect(() => {
browser.storage.local.get("words")
.then((() => words !== undefined && browser.storage.local.set({ words: words })));
}, [words]);
useEffect(() => {
browser.storage.local.get("advanced")
.then((() => advanced !== undefined && browser.storage.local.set({ advanced: advanced })));
}, [advanced]);
useEffect(() => {
browser.storage.local.get("flags")
.then((() => flags !== undefined && browser.storage.local.set({ flags: flags })));
}, [flags]);
// Show Loading till all values are synced from storage to state
if ([advanced, words, regex, flags].map(i => i === undefined).reduce((i, j) => i || j))
return <div>Loading</div>;
return ( return (
<> <>
<input <input