'localStorage solution for pagination not working

My objective here is to solve a bug where a user clicks the handleNextButton event handler via a right facing chevron > and when landing on page 40, clicks a particular patient in this table of patients. The expectation is to click the breadcrumb in the top left called Patients and get redirected back to page 40, but instead, it takes the user back to page 1 of the patients table.

I decided to store pagination state inside of localStorage, but its not working.

import React, { useEffect } from 'react'
import PatientsTable from 'components/patients/PatientsTable'
import useSWRWithToken from 'hooks/useSWRWithToken'
import Feedback from 'components/feedback'

function Patients(props) {
  const { data: patientsList, error: patientsListError } =
    useSWRWithToken('/patients')
  const { page, rowsPerPage, onRowsPerPage, onPageChange } = props

  useEffect(() => {
    if (localStorage.patientList) {
      const options = JSON.parse(localStorage.patientsList)
      if (options.page) onPageChange(options.page)
      if (options.rowsPerPage) onRowsPerPage(options.onRowsPerPage)
    }
  }, [onRowsPerPage, onPageChange])

  useEffect(() => {
    function setLocalKey(key, value) {
      localStorage.setItem(key, JSON.stringify(value))
    }

    const { patientsList } = localStorage

    // If this key exists, we need to compare it against state
    if (patientsList) {
      const options = JSON.parse(localStorage.patientsList)
      if (options.rowsPerPage !== rowsPerPage || options.page !== page) {
        setLocalKey(`patientsList`, {
          rowsPerPage: options.rowsPerPage,
          page: options.page,
        })
      }
    } else {
      setLocalKey('patientsList', { rowsPerPage, page })
    }
  }, [page, rowsPerPage, onRowsPerPage, onPageChange])

  return (
    <>
      <Feedback />
      <PatientsTable
        patientsList={patientsList}
        patientsListError={patientsListError}
      />
    </>
  )
}

Patients.layout = 'fullScreen'
Patients.auth = true
export default Patients


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source