How to Schedule RTK cache invalidation?

37 Views Asked by At

I need to check some date in saved state (localstorage) when application starts, then if it's in past - reset whole state. If it's still in future, check a bit later and repeat. Sometimes there is no date and the date appears later after some action.

There are 3 cases when we need to reset state (or schedule next check):

  1. app starts (sometimes we have date chosen already, sometimes not)
  2. app stays open (or opened again in future, we need to check date, and reset or schedule date checks)
  3. action to pick a date (we need to schedule date checks after this)

I want to have it in some kind of middleware, or in store/api endpoint config. Not to spread this logic to several places, having 3 checks and timeouts setup.

Where to add it? Is there some kind of dynamic cache invalidation or existing functionality to add similar feature?

1

There are 1 best solutions below

0
On

So far my solution is to put scheduled checks to appilication root element. But I would eager to see the solution on Redux/RTK libs level rather this such crude ones.

  useEffect(() => {
    // other app start logic here

    dispatch(checkSelectedDate())
    setInterval(() => {
      dispatch(checkSelectedDate())
    }, DATE_SELECTION_CHECK_TEMEOUT)
  }, [])

checkSelectedDate(state) {
  if (state.date && isPast(state.date)) return cleanState
  return state
}

If one has better/robust solutions please post as answer.