Refactor ObjectTable component to improve real-time update handling

- Updated subscription methods to use more descriptive names for clarity.
- Simplified the new event handler to always reload data on updates.
- Enhanced code readability by restructuring useEffect dependencies and callback functions.
This commit is contained in:
Tom Butcher 2025-08-18 01:03:05 +01:00
parent dcf90469f4
commit b4763e01af

View File

@ -57,8 +57,12 @@ const ObjectTable = forwardRef(
ref ref
) => { ) => {
const { token } = useContext(AuthContext) const { token } = useContext(AuthContext)
const { fetchObjects, connected, subscribeToObject, subscribeToType } = const {
useContext(ApiServerContext) fetchObjects,
connected,
subscribeToObjectUpdates,
subscribeToObjectTypeUpdates
} = useContext(ApiServerContext)
const isMobile = useMediaQuery({ maxWidth: 768 }) const isMobile = useMediaQuery({ maxWidth: 768 })
const navigate = useNavigate() const navigate = useNavigate()
var adjustedScrollHeight = scrollHeight var adjustedScrollHeight = scrollHeight
@ -286,14 +290,9 @@ const ObjectTable = forwardRef(
) )
}, []) }, [])
const newEventHandler = useCallback( const newEventHandler = useCallback(() => {
(newData) => { reload()
if (newData.type == type) { }, [reload, type])
reload()
}
},
[reload, type]
)
// Subscribe to real-time updates for all items // Subscribe to real-time updates for all items
useEffect(() => { useEffect(() => {
@ -305,7 +304,7 @@ const ObjectTable = forwardRef(
if (page?.items && page?.items?.length > 0) { if (page?.items && page?.items?.length > 0) {
page.items.forEach((item) => { page.items.forEach((item) => {
if (!item.isSkeleton) { if (!item.isSkeleton) {
const unsubscribe = subscribeToObject( const unsubscribe = subscribeToObjectUpdates(
item._id, item._id,
type, type,
updateEventHandler updateEventHandler
@ -325,18 +324,18 @@ const ObjectTable = forwardRef(
}) })
} }
} }
}, [pages, type, subscribeToObject, updateEventHandler, connected]) }, [pages, type, subscribeToObjectUpdates, updateEventHandler, connected])
useEffect(() => { useEffect(() => {
if (connected == true) { if (connected == true) {
const unsubscribe = subscribeToType(type, newEventHandler) const unsubscribe = subscribeToObjectTypeUpdates(type, newEventHandler)
return () => { return () => {
if (unsubscribe) { if (unsubscribe) {
unsubscribe() unsubscribe()
} }
} }
} }
}, [type, subscribeToType, connected, newEventHandler]) }, [type, subscribeToObjectTypeUpdates, connected, newEventHandler])
const updateData = useCallback( const updateData = useCallback(
(_id, updatedData) => { (_id, updatedData) => {