diff --git a/popup/src/App.js b/popup/src/App.js index b128052..798600b 100644 --- a/popup/src/App.js +++ b/popup/src/App.js @@ -1,15 +1,73 @@ /* global browser */ -import React, { useState } from 'react'; +import React, { useState, useEffect } from 'react'; function App() { - const [ advanced, setAdvanced ] = useState(false); - const [ words, setWords ] = useState([]); + const [ advanced, setAdvanced ] = useState(undefined); + const [ words, setWords ] = useState(undefined); const [ word, setWord ] = useState(""); - const [ regex, setRegex ] = useState(""); - const [ flags, setFlags ] = useState(""); + const [ regex, setRegex ] = useState(undefined); + const [ flags, setFlags ] = useState(undefined); function removeWord(idx) { 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