Search code examples
datatableserver-sideprimereact

Server-side sort with primereact datatable


I try to do a datatable with server-side rendering. I use primereact datatable v9.5

I have a problem with multi-column sort : data recieved from server are correct but primereact sorts data again. So I

For example, a part of data.

data = [{id:1, name:"alex"},
{id:2, name:"124"},
{id:3, name:"5"}]

I want to sort by name Server response :

[{id:3, name:"124"},
{id:2, name:"5"},
{id:1, name:"alex"}]

And displayed data :

[{id:2, name:"5"},
{id:3, name:"124"},
{id:1, name:"alex"}]

Here is a part of my code :

function DatatableContacts(props: {
  data: Array<ContactInterface>
  totalRecords: number
  loading: boolean
}) {
  const [data, setData] = useState(props.data) //données à afficher

  const [first1, setFirstRow] = useState(0)
  const [rowsPerPage, setRowsPerPage] = useState(10)
  const [nbDataDisplayed, setNbDataDisplayed] = useState(props.totalRecords)
  //initialisation du tri
  const [sortMeta, setSortMeta] = useState([])

  //fonction appel API
  const fetchData = async (
    page: number,
    itemsPerPage: number,
    sort?: Array<{ field: string; order: number }>
  ) => {
    //function to get data from API
setData(fetchedData)
  }


  const handleSort = async (e: any) => {
    setSortMeta(e.multiSortMeta)
    await fetchData(1, rowsPerPage, e.multiSortMeta)
    setFirstRow(0)
  }


  return (
    <>
      <DataTable
        value={data}
        rows={rowsPerPage}
        first={first1}
        multiSortMeta={sortMeta}
        sortMode="multiple"
        responsiveLayout="scroll"
        dataKey="id"
        loading={isLoading}
        removableSort
        onSort={handleSort}
      >
        <Column
          field="id"
          header={t('contacts.id')}
        ></Column>
        <Column
          field="person.firstname"
          header={t('contacts.firstname')}
          sortable
        ></Column>
        <Column
          field="person.lastname"
          header={t('contacts.lastname')}
          sortable
        ></Column>

      </DataTable>
    </>
  )
}


Solution

  • I add lazy to datatable and it is ok