refactor: Improve react webapp state management

* Add queryTextResetTime as part of the CannedQuery state
  (the QueryControl compares the canned query click time with the time of the
  last user input, and applies the text from the most recent change)

* Replace 'isRunning' (bool) with a 'queryState' (string) to reflect the subscription status
  value received from the server. Less indirection this way.

* Replace inappropriate useMemo call w/ useEffect
This commit is contained in:
John Colvin committed 2024-10-14 17:21:46 +00:00
1 parent 96dee6ac0e
commit 3b4e424dd3
3 files changed
+52 -36

No files matched your search

@@ -2,7 +2,7 @@ import { ThemeProvider, CssBaseline, GlobalStyles } from '@mui/material';
import useMediaQuery from '@mui/material/useMediaQuery';
import QueryControl from './QueryControl';
import ReactDataGrid from './ReactDataGrid';
import { useState, useMemo } from 'react';
import { useState, useEffect } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
import Sidebar from './SideBar';
import getTheme from './Theme';
@@ -58,14 +58,16 @@ const App = () => {
},
};
const [blueTable, setBlueTable] = useState({columns: null, rows: null });
const [queryInputText, setQueryInputText] = useState(null);
const [queryError, setQueryError] = useState(null);
const [isRunning, setIsRunning] = useState(false);
const [queryState, setQueryState] = useState("Unsubscribed");
const [sidebarIsOpen, setSidebarIsOpen] = useState(false);
const [cannedQuery, setCannedQuery] = useState(null);
const onCannedQueryClicked = (cannedQuery) => {
console.info(`Executing canned query: ${JSON.stringify(cannedQuery)}`);
setQueryInputText(cannedQuery.query.join("\n"));
const queryText = cannedQuery.query.join("\n");
setCannedQuery({queryText: queryText, clickTime: Date.now()});
subscribe(queryText);
};
const { sendJsonMessage, getWebSocket, readyState } = useWebSocket(
@@ -75,7 +77,8 @@ const App = () => {
onClose: () => console.info(`WebSocket closed.`),
shouldReconnect: () => true,
});
useMemo(() => {
useEffect(() => {
console.info(`WebSocket readyState: ${readyState}`)
if (readyState != ReadyState.OPEN) {
return;
@@ -84,13 +87,11 @@ const App = () => {
ws.onmessage = e => {
console.info(`Received message: ${e.data}`);
const msg = JSON.parse(e.data);
setQueryError(msg.error);
if (msg.error != null) {
setQueryError(msg.error);
return;
}
setQueryError(null);
if (msg.id != null) {
setIsRunning(msg.result.status == "Subscribed");
setQueryState("Error");
} else if (msg.id != null) {
setQueryState(msg.result.status);
} else {
console.info(`Received rows: ${msg.params.all}`);
setBlueTable({columns: msg.params.columns, rows: msg.params.all});
@@ -153,8 +154,9 @@ const App = () => {
<div style={{width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
<div style={{width: '90%', rightMargin: '100px' }}>
<QueryControl
isRunning={isRunning}
queryInputText={queryInputText}
queryState={queryState}
queryText={cannedQuery?.queryText}
queryTextResetTime={cannedQuery?.clickTime}
subscribe={subscribe}
unsubscribe={unsubscribe} />
</div>
@@ -1,6 +1,6 @@
import PropTypes from 'prop-types';
import DataTable from './DataTable';
import { useRef, useEffect } from 'react';
import { useRef, useState, useEffect } from 'react';
import { useGridApiRef } from '@mui/x-data-grid';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
@@ -12,17 +12,21 @@ import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
const QueryControl = (props) => {
const { isRunning, queryInputText, subscribe, unsubscribe } = props;
const { queryState, queryText, queryTextResetTime, subscribe, unsubscribe } = props;
// const theme = useTheme();
let textInput = useRef();
const [queryTextChangeTime, setQueryTextChangeTime] = useState(null);
useEffect(() => {
if (queryInputText == null || textInput.current == null) {
if (queryText == null || textInput.current == null) {
return;
}
// Init text field (unless a non-empty string is already present).
textInput.current.value = queryInputText;
}, [queryInputText, subscribe]);
console.info(`Initializing query input form with text: ${queryInputText}`)
// Init text field (unless a non-empty string is already present, or the user has modified
// the query - we don't want to overwrite their changes).
if (queryTextChangeTime == null || queryTextResetTime > queryTextChangeTime) {
textInput.current.value = queryText;
}
}, [queryText, queryTextChangeTime, queryTextResetTime]);
console.info(`Initializing query input form with text: ${queryText}`)
const onClearClick = () => {
textInput.current.value = '';
};
@@ -43,6 +47,11 @@ const QueryControl = (props) => {
}
};
const onChange = (e) => {
// So we know not to overwrite the changes with the canned query on re-render
setQueryTextChangeTime(Date.now());
};
return (
<Box sx={{ display: "flex", flexFlow: "column" }}>
<Paper elevation={3} sx={{ color: 'primary.main' }}>
@@ -52,6 +61,7 @@ const QueryControl = (props) => {
multiline
rows={10}
variant="outlined"
onChange={onChange}
onKeyDown={onKeyDown}
inputRef={textInput}
placeholder="Enter Query..."
@@ -69,8 +79,8 @@ const QueryControl = (props) => {
<Grid item>
<Tooltip title="Run (Ctrl+Enter)">
<Button onClick={onRunClick} sx={{
color: `query_start_button.${isRunning ? 'active' : 'inactive'}.color`,
bgcolor: `query_start_button.${isRunning ? 'active' : 'inactive'}.background_color`,
color: `query_start_button.${queryState}.color`,
bgcolor: `query_start_button.${queryState}.background_color`,
padding: '11px'
}}>
<PlayArrowIcon />
@@ -80,8 +90,8 @@ const QueryControl = (props) => {
<Grid item>
<Tooltip title="Stop">
<Button onClick={onStopClick} sx={{
color: `query_stop_button.${isRunning ? 'inactive' : 'active'}.color`,
bgcolor: `query_stop_button.${isRunning ? 'inactive' : 'active'}.background_color`,
color: `query_stop_button.${queryState}.color`,
bgcolor: `query_stop_button.${queryState}.background_color`,
padding: '11px'
}}>
<StopIcon />
@@ -99,7 +109,9 @@ QueryControl.propTypes = {
columns: PropTypes.array,
rows: PropTypes.array,
isRunning: PropTypes.bool,
queryInputText: PropTypes.string,
queryText: PropTypes.string,
queryTextResetTime: PropTypes.number,
queryState: PropTypes.string,
subscribe: PropTypes.func,
unsubscribe: PropTypes.func,
};
@@ -25,19 +25,21 @@ const Sidebar = ({ onSelection, onOpened, onClosed }) => {
}
}
};
// const onMenuItemClick = (event, cannedQuery) => {
// console.info(`menu item clicked: ${cannedQuery.name}`);
// onSelection(cannedQuery);
// };
const onMenuItemClick = async (event, cannedQuery) => {
try {
await navigator.clipboard.writeText(cannedQuery.query.join("\n"));
alert(`Copied ${cannedQuery.name} to clipboard`);
} catch (err) {
console.error('Failed to copy query text: ', err);
}
const onMenuItemClick = (event, cannedQuery) => {
console.info(`menu item clicked: ${cannedQuery.name}`);
onSelection(cannedQuery);
};
// const onMenuItemClick = async (event, cannedQuery) => {
// try {
// await navigator.clipboard.writeText(cannedQuery.query.join("\n"));
// alert(`Copied ${cannedQuery.name} to clipboard`);
// } catch (err) {
// console.error('Failed to copy query text: ', err);
// }
// };
useEffect(() => {
const fetchCannedQueries = async () => {
try {