Last active
September 25, 2021 12:52
-
-
Save wonglok/0b2ad89ea77a9bed603e6277a8a40e48 to your computer and use it in GitHub Desktop.
Shallow Store
This file contains 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 { useEffect, useState } from "react"; | |
export const getID = function () { | |
return ( | |
"_" + | |
Math.random().toString(36).substr(2, 9) + | |
Math.random().toString(36).substr(2, 9) | |
); | |
}; | |
export const ShallowStoreMethods = { | |
onEvent: () => {}, | |
makeKeyReactive: () => {}, | |
reloadKey: () => {}, | |
}; | |
/** | |
* @returns {ShallowStoreMethods} | |
*/ | |
export const makeShallowStore = (myObject = {}) => { | |
let ___NameSpaceID = getID(); | |
let Utils = { | |
exportJSON: () => { | |
return JSON.parse(JSON.stringify(myObject)); | |
}, | |
/* */ | |
getNameSpcaeID: () => { | |
return ___NameSpaceID; | |
}, | |
/* */ | |
onEvent: (key, func) => { | |
let evName = `${___NameSpaceID}`; | |
let hh = () => { | |
func(myObject[key]); | |
}; | |
window.addEventListener(`${evName}-${key}`, hh); | |
return () => { | |
window.removeEventListener(`${evName}-${key}`, hh); | |
}; | |
}, | |
makeKeyReactive: (key) => { | |
let [vv, setSt] = useState(0); | |
useEffect(() => { | |
let evName = `${___NameSpaceID}`; | |
let hh = () => { | |
setSt((s) => { | |
return s + 1; | |
}); | |
}; | |
window.addEventListener(`${evName}-${key}`, hh); | |
return () => { | |
window.removeEventListener(`${evName}-${key}`, hh); | |
}; | |
}, [vv]); | |
}, | |
reloadKey: (key) => { | |
window.dispatchEvent( | |
new CustomEvent(`${___NameSpaceID}-${key}`, { detail: {} }) | |
); | |
}, | |
}; | |
let proxy = new Proxy(myObject, { | |
get: (o, k) => { | |
// | |
if (Utils[k]) { | |
return Utils[k]; | |
} | |
return o[k]; | |
}, | |
set: (o, key, val) => { | |
let currentVal = o[key]; | |
if (currentVal !== val) { | |
o[key] = val; | |
if (typeof window !== "undefined") { | |
window.dispatchEvent( | |
new CustomEvent(`${___NameSpaceID}-${key}`, { detail: {} }) | |
); | |
} | |
} | |
return true; | |
}, | |
}); | |
let Type = { | |
...myObject, | |
...ShallowStoreMethods, | |
}; | |
/** @type {Type} */ | |
return proxy; | |
}; | |
/* Usage demo: */ | |
let UI = makeShallowStore({ | |
name: "lok", | |
}); | |
function Compo() { | |
UI.makeKeyReactive("name"); | |
return <div>{UI.name}</div>; | |
} | |
function Compo2() { | |
return ( | |
<div> | |
<button | |
onClick={() => { | |
UI.name = "ha " + Math.random(); | |
}} | |
></button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment