komarovalexander / ka-table

Lightweight MIT React Table component with Sorting, Filtering, Grouping, Virtualization, Editing and many more
http://ka-table.com
MIT License
769 stars 56 forks source link

Cannot change pageIndex through useState #431

Closed CplShepherdFIT closed 2 months ago

CplShepherdFIT commented 2 months ago

I'm trying to save pageIndex to session storage, so I have a useState [pageIndex, setPageIndex]. Next, I have

const table = useTable(...
onDispatch:
if (action.type === ActionType.UpdatePageIndex) {
    setPageIndex(action.pageIndex);
}

and

<Table
table={table}
paging={{
    pageIndex: pageIndex,
    enabled: true,
    pageSize: 10,
    position: PagingPosition.Bottom,
}}

With this setup the pageIndex gets reset to 0 every time I reload the page. I have tried all sorts of different solutions, one has worked for one refresh, the other seems to switch the paging for a second and then switch back and so on.

komarovalexander commented 2 months ago

Hi @CplShepherdFIT looks like instead of useState you have to store data in sessionStorage. (example with localStorage https://komarovalexander.github.io/ka-table/#/state-storing)

CplShepherdFIT commented 2 months ago

Is there any reason why the UpdatePageIndex action is triggered when the component initially renders? image

komarovalexander commented 2 months ago

can you reproduce that on https://stackblitz.com/edit/table-paging-ts?file=Demo.tsx ?

CplShepherdFIT commented 2 months ago

I could not reproduce that issue there. I have ended up with the following code:

const table: ITableInstance = useTable({
        onDispatch: async (action) => {
            if (action.type === ActionType.ComponentDidMount) {
                table.showLoading();
                axios.get(apiURL + '/sklad')
                .then((response) => response.data)
                .then((data) => {
                    setDataLoaded(true);
                    setData(data);
                    if (data.length / 10 <= pageIndex) {
                        setPageIndex(0);
                    }
                    console.log(data);
                })
                .catch((error) => {
                    console.error(error);
                    toast.error("Nepodarilo sa načítať dáta zo servera.", { position: "top-right" })
                })
                .finally(() => {
                    table.hideLoading();
                });
            }

            if (action.type === ActionType.UpdatePageIndex && dataLoaded) {
                setPageIndex(action.pageIndex);
            }
        }
    });

I suspect now that using setData(data) triggered an UpdatePageIndex action, since the paging had to change to accomodate the data ? (Data is used in <Table data={data} ... )

This now seems to be working.