Skip to content

useObservable doesn't update if a change appear before the hook executionΒ #5

@GuillaumeJasmin

Description

@GuillaumeJasmin

Is this a regression?

No

Description

When a stream is updated before the subscription in the hook lifecycle, the value is not updated:

const store$ = new BehaviorSubject('A');

export function Demo() {
  useEffect(() => {
    store$.next('B');
  }, []);

  const [data] = useObservable(store$);

  return <span>{data}</span>;
}

Result: A is rendered ❌

However if the subscription appear first, it works

const store$ = new BehaviorSubject('A');

export function Demo() {
  const [data] = useObservable(store$);

  useEffect(() => {
    store$.next('B');
  }, []);

  return <span>{data}</span>;
}

Result: B is rendered βœ… .

I spent a lot of time to understand why my data was not updated, and I finally spot this difference 🀯 .
After a look at the code, I understood why: the subscribe() is done inside a useEffect, and so executed after the first useEffect, but we never recheck the value of the first emission inside the subscribe.

To fix it, we need to ensure that the value has not changed immediately after the subscription:

subscription.current = sourceRef.subscribe({
  next(value) {
    if (emitsInitialSyncValue && firstEmission) {
      firstEmission = false;
+      if (value !== nextValue.current) {
+        nextValue.current = value;
+        forceUpdate();
+      }
    } else {
      nextValue.current = value;
      forceUpdate();
    }
  },
  error: setError,
  complete: setCompleted.bind(null, true),
});

What do you think ?

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

No response

Anything else?

No response

Do you want to create a pull request?

No

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions