Skip to content

Commit

Permalink
Merge pull request #164 from react-spring/fix-detect-state-change-bef…
Browse files Browse the repository at this point in the history
…ore-subscription

fix: detect state change before subscription
  • Loading branch information
dai-shi authored Aug 26, 2020
2 parents 03833e8 + 6418d36 commit a2547bb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
18 changes: 9 additions & 9 deletions .size-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@
"gzipped": 354
},
"index.js": {
"bundled": 3974,
"minified": 1304,
"gzipped": 642,
"bundled": 4173,
"minified": 1360,
"gzipped": 672,
"treeshaked": {
"rollup": {
"code": 14,
Expand All @@ -53,14 +53,14 @@
}
},
"index.cjs.js": {
"bundled": 5287,
"minified": 2019,
"gzipped": 859
"bundled": 5494,
"minified": 2072,
"gzipped": 886
},
"index.iife.js": {
"bundled": 5530,
"minified": 1695,
"gzipped": 763
"bundled": 5747,
"minified": 1757,
"gzipped": 795
},
"shallow.js": {
"bundled": 644,
Expand Down
11 changes: 8 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ export default function create<TState extends State>(
const equalityFnRef = useRef(equalityFn)
const erroredRef = useRef(false)

const state = api.getState()
if (currentSliceRef.current === undefined) {
currentSliceRef.current = selector(api.getState())
currentSliceRef.current = selector(state)
}

let newStateSlice: StateSlice | undefined
Expand All @@ -57,7 +58,7 @@ export default function create<TState extends State>(
erroredRef.current
) {
// Using local variables to avoid mutations in the render phase.
newStateSlice = selector(api.getState())
newStateSlice = selector(state)
hasNewStateSlice = !equalityFn(
currentSliceRef.current as StateSlice,
newStateSlice
Expand All @@ -74,7 +75,8 @@ export default function create<TState extends State>(
erroredRef.current = false
})

useIsoLayoutEffect(() => {
const stateBeforeSubscriptionRef = useRef(state)
useEffect(() => {
const listener = () => {
try {
const nextStateSlice = selectorRef.current(api.getState())
Expand All @@ -93,6 +95,9 @@ export default function create<TState extends State>(
}
}
const unsubscribe = api.subscribe(listener)
if (api.getState() !== stateBeforeSubscriptionRef.current) {
listener() // state has changed before subscription
}
return unsubscribe
}, [])

Expand Down

0 comments on commit a2547bb

Please sign in to comment.