Skip to content

Commit 997cf46

Browse files
committed
fix: resolve state as primitive types
1 parent 2760b70 commit 997cf46

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

src/reworm.tsx

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import makeSubject from 'callbag-subject'
44
import equal from 'fast-deep-equal'
55
import merge from 'deepmerge'
66

7+
const isPrimitive = (test: any) => test !== Object(test)
8+
79
type PrevState<T> = (prevState: T) => T
810
type GetFn<T> = (state: T) => React.ReactNode
911

@@ -35,10 +37,11 @@ export function create<T = any>(initial: T = {} as T): State<T> {
3537
return this.props.children(STATE)
3638
}
3739
private update = (next: T): void => {
38-
const newState = merge(STATE, next)
40+
const newState = !isPrimitive(next) ? merge(STATE, next) : next
41+
const isEqual = !isPrimitive ? equal(STATE, newState) : STATE === newState
3942

40-
if (!equal(STATE, newState)) STATE = newState
41-
this.setState({})
43+
if (!isEqual) STATE = newState
44+
this.forceUpdate()
4245
}
4346
}
4447

test/reworm.test.tsx

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,28 @@ describe('State', () => {
8181
'<div><div>Michael</div><input value="Michael"></div>'
8282
)
8383
})
84+
85+
it('should modify state with primitive types', () => {
86+
const initial = 'John'
87+
const user = create(initial)
88+
89+
const Users = () => <div>{user.get(val => val)}</div>
90+
const App = () => (
91+
<div>
92+
<Users />
93+
{user.get(val => (
94+
<input value={val} onChange={ev => user.set(ev.target.value)} />
95+
))}
96+
</div>
97+
)
98+
99+
const result = mount(<App />)
100+
const input = result.find('input')
101+
102+
input.simulate('change', { target: { value: 'Michael' } })
103+
104+
expect(result.html()).toEqual(
105+
'<div><div>Michael</div><input value="Michael"></div>'
106+
)
107+
})
84108
})

0 commit comments

Comments
 (0)