fleet/frontend/context/table.tsx
RachelElysia b85fbcbc83
Table Checkboxes: Checkboxes uncheck only on success notification (#1707)
- Uses Context API to track state
- resetSelectedRows default to false and only momentarily becomes true upon successful notification

Several other ideas were explored and ruled out including: asyncDebounce (impossible approach), applying state throughout the app (not concise nor maintainable), modifications directly to DataTable only (react-table did not have the right key combinations to reset selected rows manually when we needed).

Closes #1540 

Co-authored by: @martavis
2021-08-18 16:58:56 -07:00

48 lines
1.1 KiB
TypeScript

import React, { createContext, useReducer, ReactNode } from "react";
type Props = {
children: ReactNode;
};
type InitialStateType = {
resetSelectedRows: boolean;
setResetSelectedRows: (update: boolean) => void;
};
const initialState = {
resetSelectedRows: false,
setResetSelectedRows: () => null,
};
const actions = {
RESET_SELECTED_ROWS: "RESET_SELECTED_ROWS",
};
const reducer = (state: any, action: any) => {
switch (action.type) {
case actions.RESET_SELECTED_ROWS:
return { ...state, resetSelectedRows: action.resetSelectedRows };
default:
return state;
}
};
export const TableContext = createContext<InitialStateType>(initialState);
const TableProvider = ({ children }: Props) => {
const [state, dispatch] = useReducer(reducer, initialState);
const value = {
resetSelectedRows: state.resetSelectedRows,
setResetSelectedRows: (resetSelectedRows: boolean) => {
dispatch({ type: actions.RESET_SELECTED_ROWS, resetSelectedRows });
},
};
return (
<TableContext.Provider value={value}>{children}</TableContext.Provider>
);
};
export default TableProvider;