I am synchronising clocks in two JavaScript clients by writing to Firestore every second and then subscribing the second remote client / "slave" to the document.
This works fine and I can read the document changes in real time based on this method of creating the document reference:
const useCloudTimer = (isMaster, opponentCCID, userCCID) => {
const dispatch = useDispatch();
const { localRemainingTimeMS, clockTimeOut } = useSelector((state) => state.clock);
const timerRef = useRef(null);
useEffect(() => {
const db = firebase.firestore();
timerRef.current = db.collection('timers').doc(`${isMaster
? userCCID + opponentCCID
: opponentCCID + userCCID
}`);
dispatch(clock(CLOCK, { cloudTimerDbRef: timerRef.current }));
}, []);
const pushTimer = async (duration) => {
try {
await timerRef.current.set({ duration });
} catch (error) {
logger.error(error, 'cloud timer');
}
};
useEffect(() => { if (isMaster) pushTimer(localRemainingTimeMS); }, [localRemainingTimeMS]);
const getTimer = async () => {
try {
const unsubscribeRemoteTimer = await timerRef.current.onSnapshot((doc) => {
if (!clockTimeOut && doc.exists) {
const duration = Number(doc.data().duration);
dispatch(clock(CLOCK, { remoteRemainingTimeMS: duration }));
}
});
if (clockTimeOut) unsubscribeRemoteTimer().then((arg) => console.log('unsubscribeRemoteTimer', arg));
} catch (error) {
logger.error(error, 'getTimer');
}
};
useEffect(() => { if (!isMaster) getTimer(); }, []);
};
export default useCloudTimer;
The problem is when I want to delete the document. If the client that did not create the document tries to delete it, what happens is that a new document is created for a split second with the same name, and then that one is deleted. Here is the exact moment this happens where you can see two documents with the same name:
A document is green when it's being written to and red when it's being deleted.
My document ref is being stored in redux and then used via the store when required:
export const deleteCloudTimer = async (timerRef) => {
if (timerRef) {
try {
await timerRef.delete();
} catch (error) {
logger.error(error, 'Error removing document: ');
}
}
};
How can my Firebase client app delete a document if it didn't create it?
Tasks requiring precision timing especially with high amounts of reads/writes are not suggested for firestore. You might consider an alternative GCP product instead?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.