adds connection toast component to app

This commit is contained in:
Mose Müller
2023-11-02 15:23:31 +01:00
parent f01ef057bf
commit 47d64243c3
8 changed files with 88 additions and 8 deletions

View File

@ -7,6 +7,7 @@ import {
} from './components/DataServiceComponent';
import './App.css';
import { Notifications } from './components/NotificationsComponent';
import { ConnectionToast } from './components/ConnectionToast';
type ValueType = boolean | string | number | object;
@ -117,6 +118,7 @@ const App = () => {
const [showNotification, setShowNotification] = useState(false);
const [notifications, setNotifications] = useState([]);
const [exceptions, setExceptions] = useState([]);
const [connectionStatus, setConnectionStatus] = useState('connecting');
// Keep the state reference up to date
useEffect(() => {
@ -143,6 +145,14 @@ const App = () => {
})
.catch(console.error); // Handle the error appropriately
socket.on('connect', () => setConnectionStatus('connected'));
socket.on('disconnect', () => {
setConnectionStatus('disconnected');
setTimeout(() => {
setConnectionStatus('reconnecting');
}, 2000);
});
socket.on('notify', onNotify);
socket.on('exception', onException);
@ -264,6 +274,7 @@ const App = () => {
addNotification={addNotification}
/>
</div>
<ConnectionToast connectionStatus={connectionStatus} />
</>
);
};

View File

@ -0,0 +1,69 @@
import React, { useEffect, useState } from 'react';
import { Toast, Button, ToastContainer } from 'react-bootstrap';
type SnackbarToast = {
connectionStatus: string;
};
export const ConnectionToast = React.memo(({ connectionStatus }: SnackbarToast) => {
const [show, setShow] = useState(true);
useEffect(() => {
setShow(true);
}, [connectionStatus]);
const handleClose = () => setShow(false);
const getToastContent = (): {
message: string;
bg: string; // bootstrap uses `bg` prop for background color
delay: number | undefined;
} => {
switch (connectionStatus) {
case 'connecting':
return {
message: 'Connecting...',
bg: 'info',
delay: undefined
};
case 'connected':
return { message: 'Connected', bg: 'success', delay: 1000 };
case 'disconnected':
return {
message: 'Disconnected',
bg: 'danger',
delay: undefined
};
case 'reconnecting':
return {
message: 'Reconnecting...',
bg: 'info',
delay: undefined
};
default:
return {
message: '',
bg: 'info',
delay: undefined
};
}
};
const { message, bg, delay } = getToastContent();
return (
<ToastContainer position="bottom-center">
<Toast
show={show}
onClose={handleClose}
delay={delay}
autohide={delay !== undefined}
bg={bg}>
<Toast.Body className="d-flex justify-content-between">
{message}
<Button variant="close" size="sm" onClick={handleClose} />
</Toast.Body>
</Toast>
</ToastContainer>
);
});