From c9cf608f789943e81bfa32b8da5f6ca4f75d5a66 Mon Sep 17 00:00:00 2001
From: Eric Bailey <git@esb.lol>
Date: Thu, 2 May 2024 20:57:51 -0500
Subject: [Clipclops] External store, suspend/resume (#3829)

* Initial working external store

* Clean up WIP, explore suspend/resume

* Clean up state, bindings, snapshots, add some logs

* Reduce snapshots, add better logic check

* Bump interval a smidge

* Remove unused type
---
 src/state/messages/index.tsx | 36 +++++++++++++++---------------------
 1 file changed, 15 insertions(+), 21 deletions(-)

(limited to 'src/state/messages/index.tsx')

diff --git a/src/state/messages/index.tsx b/src/state/messages/index.tsx
index cdc5a4db2..22c4242e2 100644
--- a/src/state/messages/index.tsx
+++ b/src/state/messages/index.tsx
@@ -1,14 +1,12 @@
-import React, {useContext, useEffect, useMemo, useState} from 'react'
+import React, {useContext, useState, useSyncExternalStore} from 'react'
 import {BskyAgent} from '@atproto-labs/api'
+import {useFocusEffect} from '@react-navigation/native'
 
-import {Convo, ConvoParams} from '#/state/messages/convo'
+import {Convo, ConvoParams, ConvoState} from '#/state/messages/convo'
 import {useAgent} from '#/state/session'
 import {useDmServiceUrlStorage} from '#/screens/Messages/Temp/useDmServiceUrlStorage'
 
-const ChatContext = React.createContext<{
-  service: Convo
-  state: Convo['state']
-} | null>(null)
+const ChatContext = React.createContext<ConvoState | null>(null)
 
 export function useChat() {
   const ctx = useContext(ChatContext)
@@ -24,7 +22,7 @@ export function ChatProvider({
 }: Pick<ConvoParams, 'convoId'> & {children: React.ReactNode}) {
   const {serviceUrl} = useDmServiceUrlStorage()
   const {getAgent} = useAgent()
-  const [service] = useState(
+  const [convo] = useState(
     () =>
       new Convo({
         convoId,
@@ -34,21 +32,17 @@ export function ChatProvider({
         __tempFromUserDid: getAgent().session?.did!,
       }),
   )
-  const [state, setState] = useState(service.state)
+  const service = useSyncExternalStore(convo.subscribe, convo.getSnapshot)
 
-  useEffect(() => {
-    service.initialize()
-  }, [service])
+  useFocusEffect(
+    React.useCallback(() => {
+      convo.resume()
 
-  useEffect(() => {
-    const update = () => setState(service.state)
-    service.on('update', update)
-    return () => {
-      service.destroy()
-    }
-  }, [service])
-
-  const value = useMemo(() => ({service, state}), [service, state])
+      return () => {
+        convo.background()
+      }
+    }, [convo]),
+  )
 
-  return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>
+  return <ChatContext.Provider value={service}>{children}</ChatContext.Provider>
 }
-- 
cgit 1.4.1

