我从事一个裸反应本机项目,我必须使用 Firebase 持久性。我使用react-native-firebase包来完成我的所有请求。
当我使用react-native-firebase/firestore离线编写然后上线时,它会与backOffice同步。
firestore().collection(col).add(data)
当我使用react-native-firebase/firestore更新数据然后上线时,它会与backOffice同步。
firestore().collection(col).doc(id).update(data)
但是当我离线写入然后更新这个新数据(离线)时,当我上线时数据就会消失,就像挂起的请求没有同步一样。
知道为什么吗?
serverTimestamp 是与 firestore 相关的相当复杂的主题,但要点是 serverTimestamp 值永远不会在客户端设置,并且始终为 null,但它只会在服务器上设置。您可以通过以下方式获取该值:
firebase.firestore.FieldValue.serverTimestamp()
设置它的代码应该是这样的:
const firestore = firebase.firestore()
const ref = firestore.collection('messages').doc('foo')
ref.set({
createdAt: firebase.firestore.FieldValue.serverTimestamp()
})
要对此有更深入的了解,请查看 Firebase 专家撰写的这篇详细文章
firestore().collection(col).add(data)
离线写入数据,然后在离线状态下更新此新数据时,当您重新上线时,挂起的更新请求可能无法正确同步。现在,由于操作顺序以及 Firebase 处理离线更新的方式,可能会发生这种情况。在某些情况下,更新请求可能会在初始写入请求之前得到处理,这会导致意外行为。为了确保一致的同步,您可以尝试在代码中更明确地处理数据更新。
我在我的一个项目中应用了类似的东西。整体代码如下:
import firestore from '@react-native-firebase/firestore';
// Define your collection and document references
const collectionRef = firestore().collection('yourCollection');
const documentRef = collectionRef.doc('yourDocumentId');
// Define the data you want to update
const updateData = {
fieldToUpdate: 'UpdatedValue',
};
// Check network connectivity (optional)
const isConnected = /* logic to check network connectivity */;
// Function to update data
const updateDataInFirestore = async () => {
if (isConnected) {
// If online, update the data directly in Firestore
await documentRef.update(updateData);
} else {
// If offline, update the data locally
// You can maintain a local copy of the data and apply the update
const currentData = /* retrieve the current data locally */;
const updatedData = { ...currentData, ...updateData };
// Store the updated data locally for later synchronization
/* logic to store updatedData locally */
}
};
// Later, when you're back online, you can synchronize the updated data
const synchronizeData = async () => {
if (isConnected) {
// Retrieve the locally updated data
const locallyUpdatedData = /* retrieve locally updated data */;
// Update the data in Firestore to reflect the local changes
await documentRef.set(locallyUpdatedData, { merge: true });
}
};
// Call the update function when needed
updateDataInFirestore();
// Call the synchronization function when you're back online
synchronizeData();
现在我首先检查网络连接,然后根据应用程序是在线还是离线来显式处理数据更新。在线时,数据会直接在 Firestore 中更新;离线时,更新会在本地应用,并存储更改,以便稍后在您重新获得连接时进行同步。 SynchronizeData 函数处理同步过程。您还可以阅读我写的这篇文章,
react-native 的离线 firestore 支持,但是我不确定它是否可以帮助您。