Server-side Sorting Integration
Explain how to integrate server-side sorting with React TanStack Table, including fetching sorted data based on user input.
const fetchSortedData = async (sorting) => {
const response = await fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ sorting }),
});
if (!response.ok) {
throw new Error('Failed to fetch sorted data');
}
return response.json();
};
Defines an asynchronous function to fetch data sorted according to user input. The 'sorting' parameter contains the sorting state from the React Table, which is sent to the server in a POST request. The server should return the sorted data.
const [data, setData] = React.useState([]);
const [sorting, setSorting] = React.useState([]);
React.useEffect(() => {
fetchSortedData(sorting).then(sortedData => {
setData(sortedData);
}).catch(error => {
console.error('Failed to fetch sorted data:', error);
});
}, [sorting]);
Uses React state hooks for storing data and sorting state. The useEffect hook listens for changes in the sorting state and fetches sorted data accordingly. Once fetched, the data state is updated with the sorted data.
const table = useReactTable({
data,
columns,
state: { sorting },
onSortingChange: setSorting,
manualSorting: true,
getCoreRowModel: getCoreRowModel(),
});
Initializes the React Table with data, column configuration, and sorting state. It sets 'manualSorting' to true, indicating server-side sorting, and defines a handler to update the sorting state based on user interactions, triggering re-fetching and rendering of data.