7

I'm using the material-table in a material-ui Stepper and the user tends to click on "next" button even though the table is still in edit mode. This results in a loss of data.

Can I somehow access the table information to check if the table/row is still in edit mode when the user clicks the "next" button?

jayarjo
  • 16,124
  • 24
  • 94
  • 138
Tom Müller
  • 71
  • 1
  • 5

2 Answers2

6

While there's no directly exposed method that would tell you if the table is editable mode or not (and I think there should be), you can still find it out, but you will have to mess a bit with it's internals. First you will need to grab the ref of the table (find tableRef property) and then the property that will help you is lastEditingRow in the state of the table.

So, having tableRef that would be: tableRef.current.state.lastEditingRow. For a table in editing mode lastEditingRow will be set to an object describing the row being edited and undefined if table is not in editing mode.

CodeSandbox with example for you: https://codesandbox.io/s/fancy-waterfall-lg2ri

jayarjo
  • 16,124
  • 24
  • 94
  • 138
  • 1
    Thanks a lot for the hint about the tableRef prop. It perfectly works for me :) I think you should also test if `tableRef.current.state.showAddRow` is false. Otherwise, the user might create a new row, fills out all the details, clicks next without saving and the data is gone. – Tom Müller Sep 28 '19 at 13:28
  • Solution worked for me. I checked not only for `tableRef?.current?.state?.lastEditingRow` but also for `tableRef?.current?.state?.showAddRow` as mentioned by @TomMüller . This solution passively waits for the user to click the button and then shows an alert. In my case I want to disable the button proactively since it's an OK button on a dialog box. I don't want users thinking they can save when the data is dirty. – Michael Osofsky Jun 15 '23 at 19:06
1

You can use a "useRef callback" and set a state hook, exemple :

// Create a state
const [isTableIsEditMode, setIsTableIsEditMode] = useState(false);
// Create a callback
const editRowRef = useCallback((editRow: React.ReactElement<any>) => setIsTableIsEditMode(!!editRow), []);
// Use the call back as a ref in your table for the Edit Row
// the ref is null if the table is not in edit mode
return <MaterialTable
        components={{
            ...
            EditRow: (props) => {
                return <MTableEditRow {...props} ref={editRowRef} />;
            },
        }}
        ...
    />
ACivilise
  • 91
  • 2
  • 5
  • Worked for adding a new row but for editing a row, the callback was called twice, once with an editRow and once with an undefined editRow. Consequently, it prevents editing the row. This is with `"@material-table/core": "^6.1.17"` – Michael Osofsky Jun 15 '23 at 19:03