1
0
mirror of https://github.com/tooot-app/app synced 2025-06-05 22:19:13 +02:00
Use websocket to constantly fetch new notifications. Also use flatlist item view to clear notification.
This commit is contained in:
Zhiyuan Zheng
2021-02-08 23:19:55 +01:00
parent 01d4e6a5b9
commit f5414412d4
22 changed files with 576 additions and 436 deletions

60
src/api/websocket.ts Normal file
View File

@ -0,0 +1,60 @@
import { QueryKeyTimeline } from '@utils/queryHooks/timeline'
import {
getLocalInstance,
updateLocalNotification
} from '@utils/slices/instancesSlice'
import { useEffect, useRef } from 'react'
import { InfiniteData, useQueryClient } from 'react-query'
import { useDispatch, useSelector } from 'react-redux'
import ReconnectingWebSocket from 'reconnecting-websocket'
const useWebsocket = ({
stream,
event
}: {
stream: Mastodon.WebSocketStream
event: 'update' | 'delete' | 'notification'
}) => {
const queryClient = useQueryClient()
const dispatch = useDispatch()
const localInstance = useSelector(getLocalInstance)
const rws = useRef<ReconnectingWebSocket>()
useEffect(() => {
if (!localInstance) {
return
}
rws.current = new ReconnectingWebSocket(
`${localInstance.urls.streaming_api}/api/v1/streaming?stream=${stream}&access_token=${localInstance.token}`
)
rws.current.addEventListener('message', ({ data }) => {
const message: Mastodon.WebSocket = JSON.parse(data)
if (message.event === event) {
switch (message.event) {
case 'notification':
const payload: Mastodon.Notification = JSON.parse(message.payload)
dispatch(
updateLocalNotification({ latestTime: payload.created_at })
)
const queryKey: QueryKeyTimeline = [
'Timeline',
{ page: 'Notifications' }
]
const queryData = queryClient.getQueryData(queryKey)
queryData !== undefined &&
queryClient.setQueryData<
InfiniteData<Mastodon.Notification[]> | undefined
>(queryKey, old => {
if (old) {
old.pages[0].unshift(payload)
return old
}
})
break
}
}
})
}, [localInstance?.urls.streaming_api, localInstance?.token])
}
export default useWebsocket