diff options
author | Anton Tananaev <anton@traccar.org> | 2022-06-13 18:47:08 -0700 |
---|---|---|
committer | Anton Tananaev <anton@traccar.org> | 2022-06-13 18:47:08 -0700 |
commit | eb850b4a17fd0eb8e02668ed4330de5c88e79880 (patch) | |
tree | 028f0661ceaa16965fba6ed697f699d56b258993 /modern/src/ServerProvider.js | |
parent | d171ec4d0c6a40a47af7870c40d1657da2b511e8 (diff) | |
download | trackermap-web-eb850b4a17fd0eb8e02668ed4330de5c88e79880.tar.gz trackermap-web-eb850b4a17fd0eb8e02668ed4330de5c88e79880.tar.bz2 trackermap-web-eb850b4a17fd0eb8e02668ed4330de5c88e79880.zip |
Refactor server initialization
Diffstat (limited to 'modern/src/ServerProvider.js')
-rw-r--r-- | modern/src/ServerProvider.js | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/modern/src/ServerProvider.js b/modern/src/ServerProvider.js new file mode 100644 index 00000000..720d0418 --- /dev/null +++ b/modern/src/ServerProvider.js @@ -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; |