Skip to content

Instantly share code, notes, and snippets.

@nyteshade
Created December 11, 2023 09:09
Show Gist options
  • Save nyteshade/0d4ad7ea76d807a639ef670493500cd7 to your computer and use it in GitHub Desktop.
Save nyteshade/0d4ad7ea76d807a639ef670493500cd7 to your computer and use it in GitHub Desktop.
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