0

I have a page that has multiple pages that contains some data, the way it works is that we take the sorting method, and the current page number, and use them in the params when fetching data, like this:

const [Sorting, setSorting] = useState<string>(''); //this is how the data should be sorted('ascending/descending')
const [CurrentPage, setCurrentPage] = useState<number>(1);
const [Data, setData] = useState<data[]>([]);

const getData = useCallback(async () => {
  try {
    const DataResponse = await getData({
      limit: 10,
      offset: 10 * (CurrentPage - 1),
      sort: Sorting ? Sorting : 'ascending',
    });
    setData(DataResponse);
  }
},[Sorting, CurrentPage]);

useEffect(() => { //I want to reset the whole page when sorting method changes
  setData([]);
  setCurrentPage(1);
},[Sorting, ScreenSize])

useEffect(() => { //fetch data as soon as the page is loaded
  getData();
},[getData])

I want to 'reset' the page (ie: resetting the current page number and data list) when the sorting method OR the ScreenSize changes.

The result I would want:

  1. First time rendering the page => fetch data with limit 10, offset 0
  2. click on page 5 => fetch data with limit 10, offset 40
  3. change the ScreenSize/ change the sorting => reset the page, fetch data with limit 10, offset 0, sort: Sorting

The thing is, changing the sorting method will trigger the change in the dependency of the getData. So, is there any good way to do the 'resetting'?

  • In your example, there are typo in `const [Sorting, setSorting] = useState('');` and in dependency array, you are using `[sorting]` – AdvMaple Apr 24 '23 at 04:28
  • Move the function to the `useEffect` or remove the dependencies of that callback – Konrad Apr 24 '23 at 07:39

1 Answers1

0

I kinda worked around it by using a useRef to store the sorting method, that way, when the sorting method changes, it only triggers the 'reset' useEffect but not the getData useCallback:

const [Sorting, setSorting] = useState<string>(''); //this is how the data should be sorted('ascending/descending')
const [CurrentPage, setCurrentPage] = useState<number>(1);
const [Data, setData] = useState<data[]>([]);

const SortingRef = useRef<string>('') //new

const getData = useCallback(async () => {
  try {
    const DataResponse = await getData({
      limit: 10,
      offset: 10 * (CurrentPage - 1),
      sort: SortingRef.current ? SortingRef.current : 'ascending',
    });
    setData(DataResponse);
  }
},[CurrentPage]);

useEffect(() => { //I want to reset the whole page when sorting method changes
  setData([]);
  setCurrentPage(1);
},[Sorting, ScreenSize])

useEffect(() => { //fetch data as soon as the page is loaded
  getData();
},[getData])

I don't know if this is good or not but at least it works for now. If anyone knows a better way to do it, please kindly let me know.