We develop a reusable table-like component with Reacts functional component style. The table holds, manages and validates it's state with React.useReducer. In each row there are several input-fields, checkboxes and action-buttons to modifiy the row/table-state.
Now there is a Save-Button somewhere else in the GUI (not a child of the table). How can the state be retrived from the table, so that it can be send (along with some other data) to a REST-Endpoint for persistence?
Our actual solution is a callback-function that will be set as a prop on the table. This function is called from inside the table-component after each rendering to publish a copy of the current state. Now the owner of this callback function gets and holds this data so that it is available in the scope of the Save-Button.
function ComponentWrapper(props)
{
const dataRef = React.useRef(props.initialData);
function onDataUpdate(newData) {
dataRef.current = newDate;
}
function saveData() {
// send dataRef.current to REST-Endpoint
}
return (
<div>
<MyTable onDataUpdate={onDataUpdate}></MyTable>
...
<button onClick={(e) => sendData()} name="save">Save</button>
</div>
);
}
function MyTable(props)
{
const [state, dispatch] = useReducer(..., props.initialData)
// ... some code to dispatch state changing actions
useEffect(() => {
const copyOfState = { ...state }
props.onDataUpdate(copyOfState);
});
return (
// table markup goes here ...
);
}
This actually works but we believe that there might be a better way for such usecases. We don't want to lift the state from the table to the ComponentWrapper because the table should be reusable and the save button might be located on a completly different place in the GUI (e.g. in a toolbar or a menu).
Any ideas on this? Thanks in advance.