0

I have two function, one for retrieve filters and format it in object, and one when table page change. The problem is when i set a new state in the handle page change function, when i call the function to get filters in the same function it is not working.

My code :

const getFilters = () => {
        var filters = [
            {'name': 'settlements.from_date', 'value': startDate.getFullYear()+'-'+(startDate.getMonth()+1)+'-'+startDate.getDate()},
            {'name': 'settlements.to_date', 'value': endDate.getFullYear()+'-'+(endDate.getMonth()+1)+'-'+endDate.getDate()},
            {'name': 'datatable|per_page', 'value': perPage },
            {'name': 'datatable|page', 'value': page },
        ];

        if(isPaid != "all") {
            filters = [
                ...filters,
                {'name': 'is_paid#having', 'value': isPaid}
            ];
        }

        if(partner != "all") {
            filters = [
                ...filters,
                {'name': 'settlements.partners_id', 'value': partner}
            ];
        }

        return filters;
    }

    const handlePageChange = page => {
        console.log('page : '+page);
        setPage(page);
        console.log(getFilters());
    };

In the function handlePageChange, the console log for page equals to the new value, but the console log for getFilters echo the past value (-1).

Someone had idea ?

tom1337
  • 228
  • 3
  • 11
  • You need to use useEffect to get the setState changes. But i wonder why dont you simply pass the page value to the function. – Monzoor Tamal Jul 21 '20 at 08:42

1 Answers1

1

From the React Docs: State Updates May Be Asynchronous

This means that your call to setPage will not immediately update the state, but React will wait until the next re-render until the new state is usable.

Put the console.log(getFilters()); in a useEffect hook, with the page variable as a dependency, and you will see the console log after each time that state change has been applied.

Luke Storry
  • 6,032
  • 1
  • 9
  • 22
  • Thanks for your help, it is working perfectly. And I must not forget that it is possible to have several useEffect in one component. – tom1337 Jul 21 '20 at 12:21
  • Yeah! Just see them as things that only get called when something in that dep-array is changed, otherwise they don't get used – Luke Storry Jul 21 '20 at 12:30