diff options
author | Anton Tananaev <anton@traccar.org> | 2024-04-06 09:22:10 -0700 |
---|---|---|
committer | Anton Tananaev <anton@traccar.org> | 2024-04-06 09:22:10 -0700 |
commit | f418231b6b2f5e030a0d2dcc390c314602b1f740 (patch) | |
tree | 10326adf3792bc2697e06bb5f2b8ef2a8f7e55fe /src/ServerProvider.jsx | |
parent | b392a4af78e01c8e0f50aad5468e9583675b24be (diff) | |
download | trackermap-web-f418231b6b2f5e030a0d2dcc390c314602b1f740.tar.gz trackermap-web-f418231b6b2f5e030a0d2dcc390c314602b1f740.tar.bz2 trackermap-web-f418231b6b2f5e030a0d2dcc390c314602b1f740.zip |
Move modern to the top
Diffstat (limited to 'src/ServerProvider.jsx')
-rw-r--r-- | src/ServerProvider.jsx | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/ServerProvider.jsx b/src/ServerProvider.jsx new file mode 100644 index 00000000..720d0418 --- /dev/null +++ b/src/ServerProvider.jsx @@ -0,0 +1,51 @@ +import React, { useState } from 'react'; +import { Alert, IconButton, LinearProgress } from '@mui/material'; +import ReplayIcon from '@mui/icons-material/Replay'; +import { useDispatch, useSelector } from 'react-redux'; +import { useEffectAsync } from './reactHelper'; +import { sessionActions } from './store'; + +const ServerProvider = ({ + children, +}) => { + const dispatch = useDispatch(); + + const initialized = useSelector((state) => !!state.session.server); + const [error, setError] = useState(null); + + useEffectAsync(async () => { + if (!error) { + try { + const response = await fetch('/api/server'); + if (response.ok) { + dispatch(sessionActions.updateServer(await response.json())); + } else { + throw Error(await response.text()); + } + } catch (error) { + setError(error.message); + } + } + }, [error]); + + if (error) { + return ( + <Alert + severity="error" + action={( + <IconButton color="inherit" size="small" onClick={() => setError(null)}> + <ReplayIcon fontSize="inherit" /> + </IconButton> + )} + > + {error} + </Alert> + ); + } + if (!initialized) { + return (<LinearProgress />); + } + return children; +}; + +export default ServerProvider; |