Created
December 11, 2023 09:09
-
-
Save nyteshade/0d4ad7ea76d807a639ef670493500cd7 to your computer and use it in GitHub Desktop.
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 { useState } from "react"; | |
function usePropertyState(obj, properties) { | |
const [_, triggerUpdate] = useState({}); | |
const [__, setObject] = useState(obj); | |
const props = properties && Array.isArray(properties) ? properties : Reflect.ownKeys(properties); | |
const propertySet = new Set(properties); | |
// Creating a proxy for the object | |
const proxy = new Proxy(obj, { | |
set(target, property, value) { | |
if (propertySet.has(property)) { | |
triggerUpdate({}); | |
} | |
Reflect.set(target, property, value); | |
return true; | |
}, | |
}); | |
return [proxy, setObject]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment