0
\$\begingroup\$

would love a review for this hook.

The context:

  • I have a "date slider", which has "today", and previous days
  • It's possible that a user leaves the app, and when he re-opens it from foreground, it's the next day
  • In a scenario like this, I'd like to reset the state.

So, to do this, I wrote up the following:

function useForegroundListener(f) {
  const appState = useRef(AppState.currentState);
  const lastOpenedDate = useRef(subHours(new Date(), 3));
  useEffect(() => {
    const sub = AppState.addEventListener("change", (nextAppState) => {
      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === "active"
      ) {
        f(lastOpenedDate.current);
        lastOpenedDate.current = new Date();
      }
      appState.current = nextAppState;
    });

    return () => sub?.remove();
  }, [f]);
}

function useForegroundingResettingState(hoursForReset, f) {
  const [state, setState] = useState(f());
  const foregroundFn = useCallback(
    (lastOpenedDate) => {
      const openedDate = new Date();
      const numHoursPassed = differenceInHours(openedDate, lastOpenedDate);
      if (numHoursPassed >= hoursForReset) {
        console.log(
          "Reset state, too much time has passed since foreground!",
          numHoursPassed,
          hoursForReset
        );
        setState(f());
      } else {
        console.log(
          "Ignoring foreground, not enought time has passed",
          numHoursPassed,
          hoursForReset
        );
      }
    },
    [hoursForReset, f]
  );
  useForegroundListener(foregroundFn);
  return [state, setState];
}

I can then do something like this:

const [date, setDate] = useForegroundingResettingState(3, () => new Date());

Now, I can use date setDate as normal, but if the user comes back from the foreground after 3 hours, this will reset

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.