如何使用asyncStorage正确保存和加载Firestore引用

时间:2019-06-08 07:22:47

标签: javascript react-native google-cloud-firestore asyncstorage

我使用Firestore引用构建了一个聊天对象,然后将该对象保存到asyncStorage(包括我以前使用的引用)中,以便将来加载。

当从存储中加载对象并尝试访问refs时,出现错误调用: chat.messagesRef.orderBy("createdAt", "desc").onSnapshot(onMessagesUpdate);

聊天对象:

{
id: someID,
messagesRef: someFirebaseRefObject
}

示例参考功能,我希望能够保存到存储中:

firebase.firestore().collection('users').doc(chatID).collection('chats').doc(currentUser.id)

我保存和加载聊天的代码如下:

export const loadChat = async(chatData, chatID, chatType) => {
  try {
    const chat = await AsyncStorage.getItem(`@chats/${chatID}`)
    if(chat !== null) {
      const chatObj = encycle(JSON.parse(chat))
      console.log('chatObj:', chatObj)
      return chatObj
    } else {
      return syncChat(chatData, chatID, chatType)
    }
  } catch(e) {
    console.log(e)
    return false
  }
}


export const storeChat = async(chatID, chat) => {
  try {
    let chatObj = JSON.stringify(decycle(chat));
    if (chatObj){
      await AsyncStorage.setItem(`@chats/${chatID}`, chatObj)
    }
    return chat
  } catch (e) {
    console.log(e)
    return false
  }
}

syncChat是一个函数,它使用新构造的引用提取数据,效果很好。但是从loadChat返回chatObj会导致错误。

如何存储Firestore参考对象,以便可以从存储中加载它们并进行调用?

错误:

blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:62559 Possible Unhandled Promise Rejection (id: 0):
TypeError: TypeError: chat.messagesRef.orderBy is not a function

This error is located at:
    in App (at CodePush.js:578)
    in CodePushComponent (at renderApplication.js:34)
    in RCTView (at View.js:45)
    in RCTView (at View.js:45)
    in AppContainer (at renderApplication.js:33)
TypeError: TypeError: chat.messagesRef.orderBy is not a function

This error is located at:
    in App (at CodePush.js:578)
    in CodePushComponent (at renderApplication.js:34)
    in RCTView (at View.js:45)
    in RCTView (at View.js:45)
    in AppContainer (at renderApplication.js:33)
    at App._this.snapshotChatMessages (blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:86747:26)
    at App.<anonymous> (blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:86727:25)
    at callCallback (blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:12900:18)
    at commitUpdateEffects (blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:12933:13)
    at commitUpdateQueue (blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:12921:9)
    at commitLifeCycles (blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:17344:17)
    at commitAllLifeCycles (blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:18567:13)
    at Object.invokeGuardedCallbackImpl (blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:8320:16)
    at invokeGuardedCallback (blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:8411:37)
    at commitRoot (blob:http://localhost:8081/38c013ea-1bea-4338-87e7-3bdf733837b6:18743:13)

0 个答案:

没有答案
相关问题