So, I have a svelte page with a table.
I am using a writable array and paginating it to display onto my table.
Declaration of my writable array and writable number for page count:
let tableData = writable<any>([]);
let currentTablePage = writable(1);
My pagination methods:
const paginatedData = (data: any[], currentPage: number) => {
const start = (currentPage - 1) * itemsPerPage;
return data.slice(start, start + itemsPerPage);
};
const fillEmptyRows = (data: any[], currentPage: number): any[] => {
const paginated = paginatedData(data, currentPage);
const emptyRows = itemsPerPage - paginated.length;
console.log(`Page ${currentPage}, Data: `, paginated);
return [...paginated, ...Array(emptyRows).fill({})];
};
This is the reactive variable that is used to display data in table:
$: paginatedTableData = fillEmptyRows(get(tableData), get(currentTablePage));
Now, I am updating the writable array in this way:
function updateTableData(table: Writable<any[]>, newData: any[]) {
console.log("NEW DATA: ", newData);
table.update((currentData: any[]) => {
newData.forEach((newItem: any) => {
const index = currentData.findIndex(item => item.id === newItem.id);
if (index !== -1) {
currentData[index] = newItem; // Update existing record
} else {
currentData.push(newItem); // Add new record
currentData = currentData;
}
});
console.log(`Updated table data: `, currentData); // Log updated data
return currentData;
});
}
I am able to see the data in newData variable here, also when its fetched from API.
But I am not able to see data on my table.
When I debug with logs, paginatedTableData is showing an array of empty objects.
I believe issue is with update method.
Because when I trigger a method that does tableData.update(currentData => [...currentData, data]);
This works!! But not my update method.
I am new to Svelte and front end development, debugged a lot and came here,
Please help!!