Search code examples
material-uimui-x-data-grid

Editable MUI X Datagrid with row and columns coming from a backend


On this page - https://mui.com/x/react-data-grid/editing/ - the DataGrid team has put an examlpe of how to have a DataGrid with an Actions column, containing buttons for Edit, Save, Cancel and Delete.

This is exactly what I'm trying to achive, but am unable to. Essentually in their examlpe they have the rows and columns of the DataGrid hardcoded in the TS source. I need them to come from the properties of an object, that is mapped to a JSON file coming from a back-end - that's all. I have a an async method getData in another file, that returns an object with rows and column properties - how do i call that method, instead of relying on the hardcoded rows and columns objects.

I'm very new to React. I tried to use a combination of useEffect, useState, useMemo, but never got anything that works. Eventually the grid stops working, e.g. clicking the Edit buttons leads to the browser saying "Page not responding".


Solution

  • First import that getData function to tour main file where you want to use this , then use useEffect() hook with no dependencies (so that function runs only on first load of the page) then create a useState object to hold the data which your function getData() is returning. And simply map this state to Data Grid.

    If you want to perform CRUD operations on these rows make sure they all have a unique id associated to them , and thats all , create functions for edit , delete with a required parameter id and modified data and send it to backend for validation and modification.

    TIP: use a MUI model when you click on any buttons like edit , delete or anything you want to do just create a new useState to track the staus of that model , const [open , setOpen] = useState(false);