useFormState function

ZardFormSnapshot useFormState({
  1. ZardFormController? form,
  2. List<Object?> listen(
    1. ZardFormSnapshot snapshot
    )?,
})

Subscribes to form-level state. Pass listen to limit which fields of the snapshot trigger a rebuild — e.g. listen: (s) => [s.isSubmitting]. The returned tuple's equality drives rebuild decisions, so listing only what your UI uses keeps it cheap.

Implementation

ZardFormSnapshot useFormState({
  ZardFormController? form,
  List<Object?> Function(ZardFormSnapshot snapshot)? listen,
}) {
  final context = useContext();
  final resolved = form ?? ZardFormScope.of(context);
  final snapshot = useState<ZardFormSnapshot>(ZardFormSnapshot.from(resolved));
  useEffect(() {
    void onChange() {
      final next = ZardFormSnapshot.from(resolved);
      if (listen == null) {
        if (snapshot.value != next) snapshot.value = next;
        return;
      }
      final prev = listen(snapshot.value);
      final now = listen(next);
      if (!listEquals(prev, now)) {
        snapshot.value = next;
      }
    }
    resolved.addListener(onChange);
    return () => resolved.removeListener(onChange);
  }, [resolved]);
  return snapshot.value;
}