Skip to content

Commit

Permalink
fix: πŸ› use synchronouse effect to subscribe to observables
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jun 23, 2019
1 parent d8a4910 commit 376eea3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
9 changes: 9 additions & 0 deletions src/useIsomorphicLayoutEffect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { useEffect, useLayoutEffect } from 'react';

/**
* `useLayoutEffect` that does not show warning on server.
* See: https://medium.com/@alexandereardon/uselayouteffect-and-ssr-192986cdcf7a
*/
const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;

export default useIsomorphicLayoutEffect;
5 changes: 3 additions & 2 deletions src/useObservable.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useEffect, useState } from 'react';
import { useState } from 'react';
import useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect';

export interface Observable<T> {
subscribe: (
Expand All @@ -13,7 +14,7 @@ function useObservable<T>(observable$: Observable<T>, initialValue: T): T;
function useObservable<T>(observable$: Observable<T>, initialValue?: T): T | undefined {
const [value, update] = useState<T | undefined>(initialValue);

useEffect(() => {
useIsomorphicLayoutEffect(() => {
const s = observable$.subscribe(update);
return () => s.unsubscribe();
}, [observable$]);
Expand Down

0 comments on commit 376eea3

Please sign in to comment.