feat: add realtime with socket.io

This commit is contained in:
Divlo
2022-01-13 18:21:45 +01:00
parent 5c03a9b944
commit 9229131c1a
14 changed files with 1707 additions and 1528 deletions

View File

@ -23,7 +23,9 @@ export const AuthenticationProvider: React.FC<PagePropsWithAuthentication> = (
const authentication = useMemo(() => {
return new Authentication(props.authentication.tokens)
}, [props.authentication.tokens])
// eslint-disable-next-line react-hooks/exhaustive-deps -- We only want to run this memo once
}, [])
useEffect(() => {
setLanguage(user.settings.language).catch(() => {})

49
tools/handleSocketData.ts Normal file
View File

@ -0,0 +1,49 @@
import { SetItems } from '../hooks/usePagination'
export interface Item {
id: number
[key: string]: any
}
export interface SocketData<T extends Item = Item> {
action: 'create' | 'update' | 'delete'
item: T
}
export interface HandleSocketDataOptions<T extends Item = Item> {
setItems: SetItems<T>
data: SocketData<T>
}
export type SocketListener = (data: SocketData) => void
export const handleSocketData = <T extends Item = Item>(
options: HandleSocketDataOptions<T>
): void => {
const { data, setItems } = options
setItems((oldItems) => {
const newItems = [...oldItems]
switch (data.action) {
case 'create': {
newItems.push(data.item)
break
}
case 'delete': {
const itemIndex = newItems.findIndex((item) => item.id === data.item.id)
if (itemIndex !== -1) {
newItems.splice(itemIndex, 1)
}
break
}
case 'update': {
const itemIndex = newItems.findIndex((item) => item.id === data.item.id)
if (itemIndex !== -1) {
newItems[itemIndex] = data.item
}
break
}
}
return newItems
})
}