Skip to content

Commit

Permalink
Update listeners outside of useEffect (on client-side only) for early…
Browse files Browse the repository at this point in the history
… catching of updates to components
  • Loading branch information
lostpebble committed Jun 27, 2020
1 parent eba1b94 commit fbe617f
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/useStoreState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export interface IUpdateRef {
setInitial: boolean;
}

const onServer = typeof window === "undefined";

function useStoreState<S = any>(store: Store<S>): S;
function useStoreState<S = any, SS = any>(
store: Store<S>,
Expand Down Expand Up @@ -47,15 +49,18 @@ function useStoreState(store: Store, getSubState?: (state: any) => any, deps?: R
// final check again before actually running state update (might prevent no-op errors with React)
if (updateRef.current.shouldUpdate) {
updateRef.current.currentSubState = nextSubState;
setUpdateTrigger(val => val + 1);
setUpdateTrigger((val) => val + 1);
}
}
};

if (!onServer) {
store._addUpdateListener(updateRef.current.onStoreUpdate!);
}
}

useEffect(() => {
updateRef.current.shouldUpdate = true;
store._addUpdateListener(updateRef.current.onStoreUpdate!);

return () => {
updateRef.current.shouldUpdate = false;
Expand Down

0 comments on commit fbe617f

Please sign in to comment.