From 721cc297034a1ef79a52c214d5bd856155bf6759 Mon Sep 17 00:00:00 2001 From: Chandler Prall Date: Fri, 6 Nov 2020 11:03:23 -0700 Subject: [PATCH] restructure cell focus update calls to avoid render side effect --- src/components/datagrid/data_grid.tsx | 49 ++++++++++++++++----------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/src/components/datagrid/data_grid.tsx b/src/components/datagrid/data_grid.tsx index c91fe99de43f..04e4b800e916 100644 --- a/src/components/datagrid/data_grid.tsx +++ b/src/components/datagrid/data_grid.tsx @@ -80,6 +80,7 @@ import { DataGridFocusContextShape, DataGridSortingContext, } from './data_grid_context'; +import { enqueueStateChange } from '../../services/react'; // Used to short-circuit some async browser behaviour that is difficult to account for in tests const IS_JEST_ENVIRONMENT = global.hasOwnProperty('_isJest'); @@ -545,27 +546,35 @@ const useFocus = ( EuiDataGridFocusedCell | undefined >(undefined); - const setFocusedCell = useCallback( - (focusedCell: EuiDataGridFocusedCell) => { - _setFocusedCell((previousCell) => { - // verify that the cell has changed - if ( - previousCell != null && - previousCell[0] === focusedCell[0] && - previousCell[1] === focusedCell[1] - ) { - return previousCell; - } + const setFocusedCell = useCallback((focusedCell: EuiDataGridFocusedCell) => { + _setFocusedCell((previousCell) => { + // verify that the cell has changed + if ( + previousCell != null && + previousCell[0] === focusedCell[0] && + previousCell[1] === focusedCell[1] + ) { + return previousCell; + } + return focusedCell; + }); + }, []); - if (previousCell) { - notifyCellOfFocusState(cellsUpdateFocus.current, previousCell, false); - } - notifyCellOfFocusState(cellsUpdateFocus.current, focusedCell, true); - return focusedCell; - }); - }, - [cellsUpdateFocus] - ); + const previousCell = useRef(undefined); + useEffect(() => { + if (previousCell.current) { + notifyCellOfFocusState( + cellsUpdateFocus.current, + previousCell.current, + false + ); + } + previousCell.current = focusedCell; + + if (focusedCell) { + notifyCellOfFocusState(cellsUpdateFocus.current, focusedCell, true); + } + }, [cellsUpdateFocus, focusedCell]); const hasHadFocus = useMemo(() => focusedCell != null, [focusedCell]);