This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
website/tools/handleSocketData.ts

64 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-08-31 21:44:33 +02:00
import type { SetItems } from '../hooks/usePagination'
import type { CacheKey } from './cache'
import { savePaginationCache } from './cache'
2022-01-13 18:21:45 +01:00
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>
cacheKey?: CacheKey
2022-01-13 18:21:45 +01:00
}
export type SocketListener = (data: SocketData) => void
export const handleSocketData = <T extends Item = Item>(
options: HandleSocketDataOptions<T>
): void => {
const { data, setItems, cacheKey } = options
console.log('socket.io data received: ', data)
2022-01-13 18:21:45 +01:00
setItems((oldItems) => {
const newItems = [...oldItems]
switch (data.action) {
case 'create': {
newItems.push(data.item)
break
}
case 'delete': {
2022-08-31 21:44:33 +02:00
const itemIndex = newItems.findIndex((item) => {
return item.id === data.item.id
})
2022-01-13 18:21:45 +01:00
if (itemIndex !== -1) {
newItems.splice(itemIndex, 1)
}
break
}
case 'update': {
2022-08-31 21:44:33 +02:00
const itemIndex = newItems.findIndex((item) => {
return item.id === data.item.id
})
2022-01-13 18:21:45 +01:00
if (itemIndex !== -1) {
newItems[itemIndex] = {
...newItems[itemIndex],
...data.item
}
2022-01-13 18:21:45 +01:00
}
break
}
}
if (cacheKey != null) {
savePaginationCache(cacheKey, newItems)
}
2022-01-13 18:21:45 +01:00
return newItems
})
}