useAutoComputedState<T> function

MutableComputedState<T> useAutoComputedState<T>(
  1. Future<T> compute(), {
  2. bool shouldCompute = true,
  3. HookKeys keys = const [],
  4. Duration debounceDuration = Duration.zero,
})

Allows for automatic refreshing of ComputedState in response to changes in keys. Refreshes also on first call.

shouldCompute can be passed to decide if compute should be called when keys change. If shouldCompute returns false, state is cleared immediately.

debounceDuration allows for setting a delay, which must pass between keys changes to trigger compute.

Implementation

MutableComputedState<T> useAutoComputedState<T>(
  Future<T> Function() compute, {
  bool shouldCompute = true,
  HookKeys keys = const [],
  Duration debounceDuration = Duration.zero,
}) {
  return useDebugGroup(
    debugLabel: 'useAutoComputedState<$T>()',
    debugFillProperties: (properties) => properties
      ..add(DiagnosticsProperty("shouldCompute", shouldCompute, defaultValue: true))
      ..add(IterableProperty("keys", keys, defaultValue: const []))
      ..add(DiagnosticsProperty("debounceDuration", debounceDuration, defaultValue: Duration.zero)),
    () {
      final state = _useComputedState(compute);
      final timerState = useState<Timer?>(null);
      final isMounted = useIsMounted();

      useEffect(() {
        state.clear();
        timerState.value?.cancel();
        timerState.value = null;
        if (shouldCompute) {
          if (debounceDuration == Duration.zero) {
            unawaited(state.refresh());
          } else {
            timerState.value = Timer(debounceDuration, () {
              if (isMounted()) {
                unawaited(state.refresh());
                timerState.value = null;
              }
            });
          }
        }
      }, [shouldCompute, ...keys]);

      return state;
    },
  );
}