useAutoComputedState<T> function
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 = hookKeysEmpty,
Duration debounceDuration = Duration.zero,
}) {
return useDebugGroup(
debugLabel: 'useAutoComputedState<$T>()',
debugFillProperties: (properties) => properties
..add(DiagnosticsProperty("shouldCompute", shouldCompute, defaultValue: true))
..add(IterableProperty("keys", keys, defaultValue: hookKeysEmpty))
..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;
},
);
}