Last active
October 15, 2023 05:58
-
-
Save vdsabev/49b3ab2daf33f2ae125c9e6e8f56a534 to your computer and use it in GitHub Desktop.
Vue's `reactive` in React
This file contains hidden or 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
const useReactive = (object, dependencies = []) => { | |
const [_, setState] = useState(0); | |
return useMemo( | |
() => toReactive(object, () => setState((state) => state + 1)), | |
dependencies | |
); | |
}; | |
const toReactive = (object, callback) => { | |
if (!object || typeof object !== 'object') return object; | |
const array = (Array.isArray(object) ? object : [object]).map((item) => { | |
const proxy = {}; | |
Object.keys(item).forEach((key) => { | |
let value = toReactive(item[key], callback); | |
Object.defineProperty(proxy, key, { | |
enumerable: true, | |
get() { | |
return value; | |
}, | |
set(v) { | |
value = toReactive(v); | |
callback(value); | |
}, | |
}); | |
}); | |
return proxy; | |
}); | |
return Array.isArray(object) ? array : array[0]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment