Skip to content

Commit

Permalink
fix(observable): use MobX helpers to bind custom action when needed
Browse files Browse the repository at this point in the history
  • Loading branch information
tobua committed Aug 31, 2021
1 parent 42d91e2 commit b6a3262
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 4 deletions.
6 changes: 3 additions & 3 deletions demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
"icon": "../logo.png"
},
"dependencies": {
"@types/react": "^17.0.11",
"@types/react-dom": "^17.0.8",
"@types/react": "^17.0.19",
"@types/react-dom": "^17.0.9",
"exmpl": "^2.2.1",
"mobx": "^6.3.2",
"mobx-react-lite": "^3.2.0",
"papua": "^0.1.22",
"papua": "^0.1.28",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
Expand Down
15 changes: 14 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { observable, IObservableArray, runInAction } from 'mobx'
import {
observable,
IObservableArray,
runInAction,
makeObservable,
action,
} from 'mobx'

type Class = { new (...args: any[]): any }

Expand All @@ -14,6 +20,13 @@ export interface NestableItem {
// Used to ensure remove bound to instance as autoBind won't work with transpilation.
const createInstance = (Base: Class, values: any) => {
const instance = new Base(values)

// When using makeAutoObservable remove will already be observable.
if (!instance.remove.isMobxAction) {
makeObservable(instance, {
remove: action.bound,
})
}
return instance
}

Expand Down
26 changes: 26 additions & 0 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,29 @@ test('Instantiation only takes place when there is data.', () => {

expect(constructorMock.mock.calls.length).toBe(2)
})

test('Remove still works even if makeAutoObservable missing.', () => {
class NestedNotBound {
value: number

constructor(value: number) {
this.value = value
}
}

class StoreNotBound {
list = nestable([1, 2, 3], NestedNotBound)

constructor() {
makeAutoObservable(this, {}, { autoBind: true })
}
}

const Data = new StoreNotBound()

expect(Data.list.length).toEqual(3)

Data.list[1].remove()

expect(Data.list.length).toEqual(2)
})

0 comments on commit b6a3262

Please sign in to comment.