-
-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Description
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
Labels
No labels