From be771d6619d8990514f747b2a028b7d6731e4a2a Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Thu, 5 Aug 2021 16:28:05 +1000 Subject: [PATCH] This would have failed if the first node we connect to is NOT store --- examples/web-chat/src/App.tsx | 48 +++++++++++++++++------------------ 1 file changed, 23 insertions(+), 25 deletions(-) diff --git a/examples/web-chat/src/App.tsx b/examples/web-chat/src/App.tsx index 7ae79dd814..32ea1e4848 100644 --- a/examples/web-chat/src/App.tsx +++ b/examples/web-chat/src/App.tsx @@ -83,10 +83,8 @@ export default function App() { const persistedNick = window.localStorage.getItem('nick'); return persistedNick !== null ? persistedNick : generate(); }); - const [ - historicalMessagesRetrieved, - setHistoricalMessagesRetrieved, - ] = useState(false); + const [historicalMessagesRetrieved, setHistoricalMessagesRetrieved] = + useState(false); useEffect(() => { localStorage.setItem('nick', nick); @@ -122,29 +120,29 @@ export default function App() { if (!waku) return; if (historicalMessagesRetrieved) return; - const connectedToStorePeer = new Promise((resolve) => - waku.libp2p.peerStore.once( - 'change:protocols', - ({ peerId, protocols }) => { - if (protocols.includes(StoreCodec)) { - resolve(peerId); - } + const checkAndRetrieve = ({ protocols }: { protocols: string[] }) => { + if (protocols.includes(StoreCodec)) { + console.log(`Retrieving archived messages}`); + setHistoricalMessagesRetrieved(true); + + try { + retrieveStoreMessages(waku, dispatchMessages).then((length) => + console.log(`Messages retrieved:`, length) + ); + } catch (e) { + console.log(`Error encountered when retrieving archived messages`, e); } - ) - ); - - connectedToStorePeer.then(() => { - console.log(`Retrieving archived messages}`); - setHistoricalMessagesRetrieved(true); - - try { - retrieveStoreMessages(waku, dispatchMessages).then((length) => - console.log(`Messages retrieved:`, length) - ); - } catch (e) { - console.log(`Error encountered when retrieving archived messages`, e); } - }); + }; + + waku.libp2p.peerStore.on('change:protocols', checkAndRetrieve); + + return () => { + waku.libp2p.peerStore.removeListener( + 'change:protocols', + checkAndRetrieve + ); + }; }, [waku, historicalMessagesRetrieved]); return (