Skip to content

Commit 6b1bccb

Browse files
feat(proxy-state-tree): now supports getters which are tracked
1 parent e6316aa commit 6b1bccb

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

packages/node_modules/proxy-state-tree/src/Proxyfier.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,12 @@ export class Proxifier {
197197
if (typeof prop === 'symbol' || prop in Object.prototype)
198198
return target[prop]
199199

200+
const descriptor = Object.getOwnPropertyDescriptor(target, prop)
201+
202+
if (descriptor && 'get' in descriptor) {
203+
return descriptor.get.call(proxifier.getProxyFromCache(path))
204+
}
205+
200206
const trackingTree = proxifier.getTrackingTree()
201207
const targetValue = target[prop]
202208
const nestedPath = proxifier.concat(path, prop)

packages/node_modules/proxy-state-tree/src/index.test.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -887,3 +887,33 @@ describe('RESCOPING', () => {
887887
expect(tree.state.foo).toBe('bar2')
888888
})
889889
})
890+
891+
describe('GETTER', () => {
892+
it('should be able to define and track getters in the tree', () => {
893+
let renderCount = 0
894+
const tree = new ProxyStateTree({
895+
user: {
896+
firstName: 'Bob',
897+
lastName: 'Goodman',
898+
get fullName() {
899+
return this.firstName + ' ' + this.lastName
900+
},
901+
},
902+
})
903+
904+
const accessTree = tree.getTrackStateTree()
905+
const mutationTree = tree.getMutationTree()
906+
907+
function render() {
908+
accessTree.track(render)
909+
accessTree.state.user.fullName
910+
renderCount++
911+
}
912+
913+
render()
914+
915+
mutationTree.state.user.firstName = 'Bob2'
916+
tree.flush()
917+
expect(renderCount).toBe(2)
918+
})
919+
})

0 commit comments

Comments
 (0)