How to use final-form - 10 common examples

To help you get started, we’ve selected a few final-form examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github airbnb / lunar / packages / forms / src / components / Form / index.tsx View on Github external
setFieldConfig(
    [name, config]: [string, Field],
    { fields, formState }: MutableState,
  ) {
    const field = fields[name];
    const initial = getIn(formState.initialValues!, name);
    const value = typeof initial === 'undefined' ? config.defaultValue : initial;

    if (!field) {
      return;
    }

    field.data.config = config;
    // @ts-ignore
    field.initial = value;
    // @ts-ignore
    field.value = value;
    field.touched = config.validateDefaultValue || false;

    // These are needed for form "reset" to work correctly!
    /* eslint-disable no-param-reassign */
    formState.initialValues = setIn(formState.initialValues!, name, value);
github frontier-forms / frontier-forms / lib / core / core.ts View on Github external
export function getFormFromSchema (
  schema: JSONSchema7,
  onSubmit: Config['onSubmit'],
  initialValues = {} // tslint:disable-line typedef
): FormApi {
  const form = createForm({
    validate: validateWithSchema(schema),
    onSubmit,
    initialValues
  });

  registerFields(form, schema);

  return form;
}
github corpusculejs / corpuscule / packages / form / src / form.js View on Github external
klass.__initializers.push(self => {
    Object.assign(self, {
      // Fields
      [$formApi]: createForm(
        formOptionResponsibilityKeys.reduce((acc, key) => {
          if (sharedProperties[key]) {
            acc[key] = self[sharedProperties[key]];
          }

          return acc;
        }, {}),
      ),
      // eslint-disable-next-line sort-keys
      [$$unsubscriptions]: [],

      // Methods
      // eslint-disable-next-line sort-keys
      [$$reset](event) {
        event.preventDefault();
        event.stopPropagation();
github airbnb / lunar / packages / forms / src / components / Form / index.tsx View on Github external
constructor(props: Props<data>) {
    super(props);

    const { initialValues, subscriptions } = props;

    // Setup our form instance
    this.form = createForm<data>({
      destroyOnUnregister: true,
      initialValues,
      mutators: {
        setFieldConfig: this.setFieldConfig,
      },
      onSubmit: this.handleSubmit,
      validate: this.handleValidate,
    });

    this.form.subscribe(this.handleStateUpdate, mapSubscriptions(subscriptions as string[]));

    // Wait until mounted
    this.form.pauseValidation();
  }
</data></data>
github final-form / final-form / examples / react / index.js View on Github external
constructor() {
    super()
    const initialState = {}
    let inConstructor = true
    this.form = createForm({ onSubmit })

    // subscribe to form changes
    this.unsubscribe = this.form.subscribe(
      formState => {
        // cannot call setState in constructor, but need to on subsequent notifications
        if (inConstructor) {
          initialState.formState = formState
        } else {
          this.setState({ formState })
        }
      },
      { active: true, pristine: true, submitting: true, values: true }
    )

    // register fields
    this.unsubscribeFields = ['firstName', 'lastName'].map(fieldName =>
github final-form / react-final-form / src / ReactFinalForm.js View on Github external
const form: FormApi = useConstant(() =&gt; {
    const f = alternateFormApi || createForm(config)
    // pause validation until children register all fields on first render (unpaused in useEffect() below)
    f.pauseValidation()
    return f
  })
github frontier-forms / frontier-forms / lib / core / core.ts View on Github external
import * as Ajv from 'ajv';
import ajv = require('ajv');
import { Config, createForm, FieldSubscription, fieldSubscriptionItems, FormApi } from 'final-form';
import { JSONSchema7 } from 'json-schema';
import { each, noop, set } from 'lodash';

export const allFieldSubscriptionItems: FieldSubscription = fieldSubscriptionItems.reduce((result, key) => {
  result[key] = true;
  return result;
},                                                                                        {});

const formatsRegistry: { [k: string]: ajv.FormatValidator } = {};

export const addFormat = (formatName: string, validator: ajv.FormatValidator) => {
  formatsRegistry[formatName] = validator;
};

// Given a definitions and a mutation, should subscribe to proper fields
export function getFormFromSchema (
  schema: JSONSchema7,
  onSubmit: Config['onSubmit'],
  initialValues = {} // tslint:disable-line typedef
): FormApi {
github final-form / react-final-form-arrays / src / useFieldArray.js View on Github external
// @flow
import { useForm, useField } from 'react-final-form'
import { fieldSubscriptionItems, ARRAY_ERROR } from 'final-form'
import type { Mutators } from 'final-form-arrays'
import type { FieldValidator, FieldSubscription } from 'final-form'
import type { FieldArrayRenderProps, UseFieldArrayConfig } from './types'
import defaultIsEqual from './defaultIsEqual'
import useConstant from './useConstant'

const all: FieldSubscription = fieldSubscriptionItems.reduce((result, key) => {
  result[key] = true
  return result
}, {})

const useFieldArray = (
  name: string,
  {
    subscription = all,
    defaultValue,
    initialValue,
    isEqual = defaultIsEqual,
    validate: validateProp
  }: UseFieldArrayConfig = {}
): FieldArrayRenderProps => {
  const form = useForm('useFieldArray')
github final-form / react-final-form-hooks / src / useFormState.js View on Github external
import { useEffect, useState } from 'react'
import { formSubscriptionItems } from 'final-form'

export const all = formSubscriptionItems.reduce((result, key) => {
  result[key] = true
  return result
}, {})

/**
 * Converts { active: true, data: false, ... } to `[true, false, false, ...]`.
 */
const subscriptionToInputs = subscription =>
  formSubscriptionItems.map(key => Boolean(subscription[key]))

const useFormState = (form, subscription = all) => {
  const [state, setState] = useState(() => form.getState())

  const deps = subscriptionToInputs(subscription)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => form.subscribe(setState, subscription), [form, ...deps])
github frontier-forms / frontier-forms / lib / react / frontier.tsx View on Github external
import { FormApi, FormState, FormSubscription, formSubscriptionItems, Unsubscribe } from 'final-form';
import { JSONSchema7 } from 'json-schema';
import { each, isEqual, memoize, set, values } from 'lodash';
import { Component, ComponentType } from 'react';
import * as React from 'react'; // tslint:disable-line no-duplicate-imports
import { getFormFromSchema, visitSchema } from '../core/core';
import { FrontierDataProps, schemaFromDataProps } from '../data';
import { saveData } from '../data/graphql';
import { UIKitAPI, UIKITFieldProps } from '../ui-kit';

export const allFormSubscriptionItems: FormSubscription = formSubscriptionItems.reduce(
  (result, key) =&gt; {
    result[key] = true;
    return result;
  },
  {}
);

export interface Modifiers {
  change: (value: any) =&gt; void; // tslint:disable-line no-any
  focus: () =&gt; void;
  blur: () =&gt; void;
}

// export type RenderPropsModifiersFieldObject = { [k: string]: RenderPropsModifiersFieldObject | Modifiers; }
// tslint:disable-next-line max-line-length
// export type RenderPropsUIKitFieldObject = { [k: string]: RenderPropsUIKitFieldObject | ComponentType; }

final-form

🏁 Framework agnostic, high performance, subscription-based form state management

MIT
Latest version published 1 year ago

Package Health Score

70 / 100
Full package analysis