Synchronizing Table State with URL Parameters
Illustrates how to synchronize table state (like sorting and pagination) with URL parameters. Includes examples of updating the URL based on state changes.
const history = useHistory();
const location = useLocation();
Initialize history and location hooks from React Router for manipulating and reading the URL.
const [tableState, setTableState] = useState({ pageIndex: 0, pageSize: 10, sortBy: '' });
Set initial table state including pagination and sorting.
useEffect(() => {
const params = new URLSearchParams(location.search);
const pageIndex = parseInt(params.get('page') || '0', 10);
const pageSize = parseInt(params.get('size') || '10', 10);
const sortBy = params.get('sort') || '';
setTableState({ pageIndex, pageSize, sortBy });
}, [location.search]);
Sync URL with table state on component mount or when URL search params change.
const updateUrlParams = ({ pageIndex, pageSize, sortBy }) => {
const params = new URLSearchParams();
params.set('page', pageIndex);
params.set('size', pageSize);
if (sortBy) params.set('sort', sortBy);
history.push({ search: params.toString() });
};
Function to update URL based on the table state changes like page size, current page, and sorting.
useEffect(() => {
updateUrlParams(tableState);
}, [tableState]);
Effect hook to watch for changes in tableState and update the URL accordingly.