useFutureRetry<T> function

FutureState<T> useFutureRetry<T>(
  1. Future<T>? future, {
  2. T? initialData,
  3. bool preserveState = true,
})

Uses useFuture with an additional retry method to easily retry/refresh the future function.

Implementation

FutureState<T> useFutureRetry<T>(
  Future<T>? future, {
  T? initialData,
  bool preserveState = true,
}) {
  final attempt = useState(0);
  final snapshotRef = useRef<AsyncSnapshot<T>>(const AsyncSnapshot.nothing());

  final snapshot = useFuture<T>(
    useMemoized(() => future, [attempt.value]),
    initialData: initialData,
    preserveState: preserveState,
  );
  snapshotRef.value = snapshot;

  final snapshotCallback = useCallback<SnapshotCallback<T>>(() {
    return snapshotRef.value;
  }, const []);

  final retry = useCallback(() {
    attempt.value++;
  }, [future, initialData, preserveState]);

  final state = useRef(FutureState(snapshotCallback, retry));

  return state.value;
}