Skip to content

Commit 8b338ed

Browse files
committed
[firestore] Backport #201 to the v4.0.x branch
1 parent 11aa6dc commit 8b338ed

File tree

2 files changed

+39
-6
lines changed

2 files changed

+39
-6
lines changed

firestore/useCollection.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ const useCollectionInternal = <T = DocumentData>(
7575
return;
7676
}
7777
if (listen) {
78-
const listener =
78+
const unsubscribe =
7979
options && options.snapshotListenOptions
8080
? onSnapshot(
8181
ref.current,
@@ -86,13 +86,30 @@ const useCollectionInternal = <T = DocumentData>(
8686
: onSnapshot(ref.current, setValue, setError);
8787

8888
return () => {
89-
listener();
89+
unsubscribe();
9090
};
9191
} else {
92+
let effectActive = true;
93+
9294
const get = getDocsFnFromGetOptions(
9395
options ? options.getOptions : undefined
9496
);
95-
get(ref.current).then(setValue).catch(setError);
97+
98+
get(ref.current)
99+
.then((result) => {
100+
if (effectActive) {
101+
setValue(result);
102+
}
103+
})
104+
.catch((error) => {
105+
if (effectActive) {
106+
setError(error);
107+
}
108+
});
109+
110+
return () => {
111+
effectActive = false;
112+
};
96113
}
97114
}, [ref.current]);
98115

firestore/useDocument.ts

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ const useDocumentInternal = <T = DocumentData>(
7474
return;
7575
}
7676
if (listen) {
77-
const listener =
77+
const unsubscribe =
7878
options && options.snapshotListenOptions
7979
? onSnapshot(
8080
ref.current,
@@ -85,14 +85,30 @@ const useDocumentInternal = <T = DocumentData>(
8585
: onSnapshot(ref.current, setValue, setError);
8686

8787
return () => {
88-
listener();
88+
unsubscribe();
8989
};
9090
} else {
91+
let effectActive = true;
92+
9193
const get = getDocFnFromGetOptions(
9294
options ? options.getOptions : undefined
9395
);
9496

95-
get(ref.current).then(setValue).catch(setError);
97+
get(ref.current)
98+
.then((doc) => {
99+
if (effectActive) {
100+
setValue(doc);
101+
}
102+
})
103+
.catch((error) => {
104+
if (effectActive) {
105+
setError(error);
106+
}
107+
});
108+
109+
return () => {
110+
effectActive = false;
111+
};
96112
}
97113
}, [ref.current]);
98114

0 commit comments

Comments
 (0)