diff options
author | Anton Tananaev <anton@traccar.org> | 2023-08-19 13:58:45 -0700 |
---|---|---|
committer | Anton Tananaev <anton@traccar.org> | 2023-08-19 13:59:07 -0700 |
commit | d3c7705bedebd65c94f9eea691aaf2fe03b0cafe (patch) | |
tree | 5f98b3d9bbbd4fe8067b5a334e84aff008b8db22 /modern/src/ServerProvider.jsx | |
parent | 0161ae449d4a7bd0781c0665d663353663ab0faf (diff) | |
download | trackermap-web-d3c7705bedebd65c94f9eea691aaf2fe03b0cafe.tar.gz trackermap-web-d3c7705bedebd65c94f9eea691aaf2fe03b0cafe.tar.bz2 trackermap-web-d3c7705bedebd65c94f9eea691aaf2fe03b0cafe.zip |
Move to Vite
Diffstat (limited to 'modern/src/ServerProvider.jsx')
-rw-r--r-- | modern/src/ServerProvider.jsx | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/modern/src/ServerProvider.jsx b/modern/src/ServerProvider.jsx new file mode 100644 index 00000000..720d0418 --- /dev/null +++ b/modern/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; |