From 2f9a1f07798f2ed24993034012330ff7893c9716 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 17 Apr 2019 16:30:29 +0300 Subject: Fix EventSource --- vnext/src/App.js | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) (limited to 'vnext/src/App.js') diff --git a/vnext/src/App.js b/vnext/src/App.js index 4e40f9f1..e461152b 100644 --- a/vnext/src/App.js +++ b/vnext/src/App.js @@ -39,25 +39,32 @@ export default function App() { }); }; - const [es, setEs] = useState(); + const [es, setEs] = useState({}); + useEffect(() => { const { hash } = visitor; if (hash) { me().then(visitor => auth(visitor)); - } - const eventParams = { hash: visitor.hash }; - let url = new URL(`https://api.juick.com/events?${qs.stringify(eventParams)}`); - let es = new EventSource(url); - es.onopen = () => { - console.log('online'); - es.addEventListener('read', updateStatus); - }; - es.onerror = () => { - es.removeEventListener('read', updateStatus); + if ('EventSource' in window) { + const eventParams = { hash: hash }; + let url = new URL(`https://juick.com/api/events?${qs.stringify(eventParams)}`); + let es = new EventSource(url); + es.onopen = () => { + console.log('online'); + }; + es.onerror = () => { + es.removeEventListener('read', updateStatus); + }; + es.addEventListener('read', updateStatus); + setEs(es); + } }; - setEs(es); - }, [visitor]); - + return (() => { + if (es.removeEventListener) { + es.removeEventListener('read', updateStatus); + } + }); + }, [visitor.hash]); let search = (history, pathname, searchString) => { let location = {}; -- cgit v1.2.3