Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: detect state change before subscription #164

Merged
merged 1 commit into from
Aug 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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