Interacting with other fields

UI extensions can interact with the other fields of the form, and with the form itself.

For these purposes, the form property exposes the following methods:

MethodSignatureDescription
change(fieldName: string, value: any) => Promise<void>changes the value of another field
getState() => Promise<FormState>returns the current form state
getFieldState(fieldName: string) => Promise<FieldState>returns the given field state
subscribeToFieldState(fieldName: string, callback: (state: FieldState, subscription: FieldSubscription) => void) => Promise<Unsubscribe>opens a subscription to a field's state changes
subscribeToFormState(callback: (state: FormState) => void, subscription: FormSubscription) => Promise<Unsubscribe>; opens a subscrition to the form's state changes
setFieldsVisibility(arg: VisibilityMap| ((currentVisibilityMap:VisibilityMap) => VisibilityMap)) => void;Allows modifying visibility of any field

TypesAnchor

Internally, Hygraph uses final-form to manage form and field states.

FormStateAnchor

See FormState on final-form.

The FormSubscription param has the same shape as FormState, but using a boolean to describe which state changes you want to subscribe to.

subscribeToFormState((state) => console.log(state.dirty, state.errors), {
// react only to form `dirty` and `invalid` state changes
dirty: true,
invalid: true,
});

FieldStateAnchor

See FormState on final-form.

The FieldSubscription param has the same shape as FieldState, but using a boolean to describe which state changes you want to subscribe to.

subscribeToFieldState('title', (state) => console.log(state.value), {
// react only to field `value` changes
value: true,
});

UnsubscribeAnchor

Both subscribeToFieldState and subscribeToFormState return a function to be called when needing to unsubscribe from changes. In order to avoid perfomance issues, make sure to unsubscribe any existing subscription before subscribing again.

Example in React:

React.useEffect(() => {
let unsubscribe;
subscribeToFieldState('title', (state) => console.log(state.value), {
value: true,
}).then((fieldUnsubscribe) => (unsubscribe = fieldUnsubscribe));
return () => {
unsubscribe?.();
};
}, []);

Set fields visibilityAnchor

type VisibilityMap = {
[fieldApiId: string]: 'READ_ONLY' | 'HIDDEN' | 'READ_WRITE';
};

Using object form to set visibility for field with API ID fieldApiId

setFieldsVisibility({
fieldApiId: 'READ_ONLY',
});

Using callback to calculate next visibility value for field with API ID fieldApiId

setFieldsVisibility((currentVisibilityMap) => {
const nextVisibilityValue =
currentVisibilityMap[fieldApiId] === 'READ_ONLY'
? 'READ_WRITE'
: 'READ_ONLY';
return {
fieldApiId: nextVisibilityValue,
};
});