Code Monkey home page Code Monkey logo

react-final-form-arrays's Introduction

💰 Wanna get paid the big bucks writing React? Take this quiz and get offers from top tech companies! 💰


🏁 React Final Form Arrays

NPM Version NPM Downloads Build Status codecov.io styled with prettier


Installation

npm install --save react-final-form-arrays react-final-form final-form final-form-arrays

or

yarn add react-final-form-arrays react-final-form final-form final-form-arrays

Usage

🏁 React Final Form Arrays provides a way to render arrays in 🏁 React Final Form.

import { Form, Field } from 'react-final-form'
import arrayMutators from 'final-form-arrays'
import { FieldArray } from 'react-final-form-arrays'

const MyForm = () => (
  <Form
    onSubmit={onSubmit}
    mutators={{
      // potentially other mutators could be merged here
      ...arrayMutators
    }}
    validate={validate}
    render={({ handleSubmit, pristine, invalid }) => (
      <form onSubmit={handleSubmit}>
        <FieldArray name="customers">
          {({ fields }) => (
            <div>
              {fields.map((name, index) => (
                <div key={name}>
                  <div>
                    <label>First Name</label>
                    <Field name={`${name}.firstName`} component="input" />
                  </div>
                  <div>
                    <label>Last Name</label>
                    <Field name={`${name}.lastName`} component="input" />
                  </div>
                  <button type="button" onClick={() => fields.remove(index)}>
                    Remove
                  </button>
                </div>
              ))}
              <button
                type="button"
                onClick={() => fields.push({ firstName: '', lastName: '' })}
              >
                Add
              </button>
            </div>
          )}
        </FieldArray>
      </form>
    )}
  />
)

Table of Contents

Examples

Demostrates how to use <FieldArray/> to render an array of inputs, as well as use push, pop, and remove mutations.

Demostrates how to integrate the simple example with react-beautiful-dnd

Rendering

There are three ways to tell <FieldArray/> what to render:

Method How it is rendered
component prop return React.createElement(this.props.component, props)
render prop return this.props.render(props)
a render function as children return this.props.children(props)

API

The following can be imported from react-final-form-arrays.

FieldArray : React.ComponentType<FieldArrayProps>

A component that takes FieldArrayProps and renders an array of fields

useFieldArray

The useFieldArray hook takes two parameters, the first is the name of the field, and the second is an optional object that looks just like FieldArrayProps, except without the name. It returns an object just like FieldArrayRenderProps.

useFieldArray is used interally inside FieldArray.

version: string

The current used version of 🏁 React Final Form Arrays.


Types

FieldArrayProps

These are props that you pass to <FieldArray/>. You must provide one of the ways to render: component, render, or children.

children?: ((props: FieldArrayRenderProps) => React.Node) | React.Node

A render function that is given FieldArrayRenderProps, as well as any non-API props passed into the <FieldArray/> component.

component?: React.ComponentType<FieldArrayRenderProps>

A component that is given FieldArrayRenderProps as props, as well as any non-API props passed into the <FieldArray/> component.

name: string

The name of your field array.

render?: (props: FieldArrayRenderProps) => React.Node

A render function that is given FieldArrayRenderProps, as well as any non-API props passed into the <FieldArray/> component.

defaultValue?: any

⚠️ You probably want initialValue! ⚠️

Before using this prop, read and understand the 🏁 Final Form documentation on initialValue and defaultValue!

initialValue?: any

See the 🏁 Final Form docs on initialValue

isEqual?: (allPreviousValues: Array<any>, allNewValues: Array<any>) => boolean

A function that can be used to compare two arrays of values (before and after every change) and calculate pristine/dirty checks. Defaults to a function that will === check each element of the array.

subscription?: FieldSubscription

A FieldSubscription that selects of all the items of FieldState that you wish to update for. If you don't pass a subscription prop, it defaults to all of FieldState.

validate?: (value: ?any[], allValues: Object) => ?any

A function that takes the field value, and all the values of the form and returns an error if the array value is invalid, or undefined if the value is valid.

FieldArrayRenderProps

These are the props that <FieldArray/> provides to your render function or component. This object is divided into a fields object that mimics an iterable (e.g. it has map() and forEach() and length), and meta data about the field array. Keep in mind that the values in meta are dependent on you having subscribed to them with the subscription prop

fields.forEach: (iterator: (name: string, index: number) => void) => void

Iterates through all of the names of the fields in the field array in bracket format, e.g. foo[0], foo[1], foo[2].

fields.insert: (index: number, value: any) => void

A function to insert a value into any arbitrary index of the array.

fields.map: (iterator: (name: string, index: number) => any) => any[]

Iterates through all of the names of the fields in the field array in bracket format, e.g. foo[0], foo[1], foo[2], and collects the results of the iterator function. You will use this in almost every implementation.

fields.move: (from: number, to: number) => void

A function to move a value from one index to another. Useful for drag-and-drop reordering.

fields.name: string

The name of the field array.

fields.pop: () => any

A function to remove a value from the end of the array. The value will be returned.

fields.push: (value: any) => void

A function to add a value to the end of the array.

fields.remove: (index: number) => any

A function to remove a value from an arbitrary index of the array.

fields.shift: () => any

A function to remove a value from the beginning of the array. The value will be returned.

fields.swap: (indexA: number, indexB: number) => void

A function to swap two values in the array.

fields.update: (index: number, value: any) => void

Updates a value of the specified index of the array field.

fields.unshift: (value: any) => void

A function to add a value to the beginning of the array.

fields.value: any[]

The value of the array. Should be treated as readonly.

meta.active?: boolean

See the 🏁 Final Form docs on active.

meta.data: Object

See the 🏁 Final Form docs on data.

meta.dirty?: boolean

See the 🏁 Final Form docs on dirty.

meta.error?: any

See the 🏁 Final Form docs on error.

meta.initial?: any

See the 🏁 Final Form docs on initial.

meta.invalid?: boolean

See the 🏁 Final Form docs on invalid.

meta.pristine?: boolean

See the 🏁 Final Form docs on pristine.

meta.submitError?: any

See the 🏁 Final Form docs on submitError.

meta.submitFailed?: boolean

See the 🏁 Final Form docs on submitFailed.

meta.submitSucceeded?: boolean

See the 🏁 Final Form docs on submitSucceeded.

meta.touched?: boolean

See the 🏁 Final Form docs on touched.

meta.valid?: boolean

See the 🏁 Final Form docs on valid.

meta.visited?: boolean

See the 🏁 Final Form docs on visited.

react-final-form-arrays's People

Contributors

bertho-zero avatar chadlefort avatar cinemaster avatar dependabot[bot] avatar erikras avatar jdimovska avatar juansasa avatar maciejmyslinski avatar maxmalov avatar michaeldeboey avatar netdown avatar ogg70 avatar perfectpixel avatar petermikitsh avatar reganl avatar rosskevin avatar shirbr510 avatar tim-mccurrach avatar vtaits avatar wlchn avatar yankovsky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-final-form-arrays's Issues

destroyOnUnregister breaks fields.remove()

Are you submitting a bug report or a feature request?

I believe this is a bug.

What is the current behavior?

After you add destroyOnUnregister and set it to true, fields.remove(index) stops working.

What is the expected behavior?

After you press remove button on item, fields.remove(index) actually remove an item.

Sandbox Link

https://codesandbox.io/s/21r85zk67r

What's your environment?

Dependencies:

final-form: 4.8.3, 
final-form-arrays: 1.0.4,
react-final-form:  3.6.2
react-final-form-arrays: 1.0.6
Browsers: Firefox, Chrome, Safari

Other information

Thank you for this top tier form library, ask anything if you need.

Using "remove" on an array row is not making form dirty

Are you submitting a bug report or a feature request?

bug report

What is the current behavior?

Have a form that has a FieldArray in it. The form has initialValues set for the array.
If you use field.remove(index) to remove a row from the FieldArray, it does not make the parent form dirty.
This is an issue where the disabled of the submit button on the form is tied to "pristine".

The final form documentation at https://github.com/final-form/react-final-form-arrays#simple-example has a link to a codesandbox at https://codesandbox.io/s/kx8qv67nk5.
In this example, if you insert the following in the <Form> tag:
initialValues={{ company: 'MinuteMe.com', customers: [ { firstName: 'Simon', lastName: 'Steele' } ] }}
You will see the form Submit button is immediately disabled - form is pristine.
Delete the Customer row, and form becomes dirty - Submit button is enabled.

NOW... This sandbox uses old versions of the libraries.

I am using newer versions, per this sandbox https://codesandbox.io/s/p34l93w81j. NOTE this sandbox already has my initialValues entered.

See that the same outcome is not achieved by deleting the row! The form is still dirty even though the row was removed.

What is the expected behavior?

Expected behaviour is that the form should be marked 'dirty' when the array row is removed.

Sandbox Link

See above.

What's your environment?

The version that fails (per sandbox link above):
"react-final-form-arrays": "1.1.0",
"react-final-form": "3.6.7",
"react-dom": "16.6.0",
"react": "16.6.0",
"final-form-arrays": "1.1.0",
"final-form": "4.10.0"

Add ability to provide FieldConfig (or at least isEqual) for FieldArray

Are you submitting a bug report or a feature request?

Feature request

What is the current behavior?

Currently it's not possible to set (in my case) custom isEqual function for FieldArray. I would like to detect changes with deepEquals to know whether something has changed. Now as I understand it's not possible.

Field Array Validation Broken with latest version of FinalForm/RFF

With the latest update all validation breaks on Field Arrays. Only thing changed in entire project is the update of these 2 packages. If I remove those packages and do nothing else, it all works again. I would like to be able to use the new form property in onSubmit so I would like to update.

Steps to reproduce

  1. Try touching the Name field, then lose focus. On the first you get required. On the second, the validate function never gets called.
  2. Try adding multiple items in the array. Still no validation.

Examples

Works
"final-form": "^1.3.5",
"react-final-form": "^1.2.1",
Edit 1q618oqw83

Doesn't work
"final-form": "^3.0.0",
"react-final-form": "^2.1.1"
Edit 8xo8yjvz69

FieldArray gives my rendered component a prop called `value`, is this a public API?

Are you submitting a bug report or a feature request?

Bug report, maybe? Docs?

What is the current behavior?

The component I pass to <FieldArray> in the component prop receives a prop called value. Is this a public/stable API?

I don't see this in FieldArrayRenderProps, either in the docs or the flow types.

What is the expected behavior?

Sandbox Link

Here's the FieldArray example, adapted to show I can read from the value prop.

https://codesandbox.io/s/n1nn8rpjwl

What's your environment?

Same as the example codesandbox.

Other information

Ultimately what I'm looking for is a way to read from the FieldArray programmatically/imperatively.

In redux-form I could use .get() and/or .getAll(), but this isn't available in react-final-form.

Any guidance?

arrays get reset with pristine values on change

Are you submitting a bug report or a feature request?

Bug report

What is the current behavior?

I have a form with the following characteristics:
My initial values are as follows:

{
    apis: []
}
<Form
    onSubmit={this.handleSubmit}
    validate={this.handleValidate}
    validateOnBlur={true}
    initialValues={{
         apis: []
    }}
    keepDirtyOnReinitialize={true}
    mutators={mutators}
    subscription={{
        value: true,
        submitting: true,
        validating: true,
    }}
    render={renderProps => (
        <React.Fragment>
            <FormDebugger form={formName} />
            {render(renderProps)}
            <FormSpy
                subscription={formSpySubscription}
                onChange={this.handleSubmitSuccess}
            />
        </React.Fragment>
    )}
    />
<FieldArray name="apis">
    {({ fields }) => (
        <React.Fragment>
            <FormControl className={classes.inputLabel}>
                <InputLabel htmlFor="api">Select an API</InputLabel>
                <Select
                    value={selected}
                    onChange={this.handleChange}
                >
                    <MenuItem key="item" value={null}>
                        Select an API
                    </MenuItem>
                    {Object.values(apiConstants)
                        .filter(
                            ky => !values.apis.find(el => el.api === ky.value)
                        )
                        .map(el => (
                            <MenuItem key={el.value} value={el.value}>
                                {el.key}
                            </MenuItem>
                        ))}
                </Select>
            </FormControl>
            <IconButton onClick={this.handleSelect(fields)}>
                <PlusIcon />
            </IconButton>
            <Table>
                <TableBody>
                    {fields.map((name, index) => (
                        <TableRow key={name}>
                            <TableCell component="th" scope="row">
                                <Field
                                    name={`${name}.api`}
                                    readOnly
                                    component={TextInput}
                                />
                            </TableCell>
                            <TableCell>
                                <Field name={`${name}.value`} component={TextInput} />
                            </TableCell>
                        </TableRow>
                    ))}
                </TableBody>
            </Table>
        </React.Fragment>
    )}
</FieldArray>

When I select an item in the Select component a state change occurs and the entire form resets with keepDirtyOnReinitialize=false or it keeps the changes with keepDirtyOnReinitialize=true but after adding a first api, the second state change causes the api[0] to be set to undefined.

What is the expected behavior?

It should not reset form state on a state change.

What's your environment?

"node": "8.12.0",
"react": "16.6.0",
"final-form": "4.11.0",
"final-form-arrays": "1.1.1",
"react-final-form": "4.0.2",
"react-final-form-arrays": "2.0.1",

lack of examples (up-to-date)

Are you submitting a bug report or a feature request?

Request

What is the current behavior?

There is only one simple example, which is outdated (versions are old)

What is the expected behavior?

Having good documented/explained examples. Covering more complex cases like: using render component, that is able to read array property in componentDidMount and update it if there is missing value. The community support in StackOverflow is really bad

Fields typing is missing "update"

Are you submitting a bug report or a feature request?

Bug

What is the current behavior?

Update method exists for fields but is not declared in typings file

What is the expected behavior?

update must be declared in typing file

Sandbox Link

What's your environment?

Other information

Field Array validation not working as expected

@erikras

As you can see the validation is returning correctly, but the form errors are not showing for the field array.

Try typing in a first name.

Also try adding 6 customers, each with just a last name. You only get 3 form errors

Edit 🏁 React Final Form - Field Arrays

`dirtySinceLastSubmit` is missing in meta

Bug Report

As title, it seems the dirtySinceLastSubmit in final form FieldState is missing when reporting to meta of FieldArray. Line 196.

Or do I misunderstand something that the meta should not contains dirtySinceLastSubmit? 🤔

how can i get fields index

hey
i have a fieldArray like this

<FieldArray name="exb_set">
    {({ fields }) =>
        <React.Fragment>
            {fields.map((name, index) => (
                <Exhibition
                    key={name}
                    name={name}
                    index={index + 1}
                    onRemoveClick={() => fields.remove(index)}
                    input={this.AdaptedInput}
                    radio={this.AdaptedRadio}
                    textarea={this.AdaptedTextarea}
                    LabelRequired={this.LabelRequired}
                    PushArt={push}
                />
            ))}
            <Col lg={12} md={12} sm={12} xs={12}>
                <div className="addSectionButton">
                    <button
                        type="button"
                        className=""
                        onClick={() => this.addExhibition(fields.push, fields.name, 'Exb', **'fields.index'**
                        )}>
                        <i></i>
                        <span>اضافه کردن نمایشگاه</span>
                    </button>
                </div>
            </Col>
        </React.Fragment>
    }
</FieldArray>

when i push fields i need to pass the current Field Index to AddExhibition() how can i do this?

How to resolve warning: Can only update a mounted or mounting component for Array

Any thoughts on how I can resolve this ? The FieldArray field is just function. And using that in my form.

 Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

Please check the code for the ReactFinalFormFieldArray(4.2.0)(undefined) component.

Does not work with React 15

Are you submitting a bug report or a feature request?

A Bug report

What is the current behavior?

The package.json allows a peer of react 15, but it does not work with React 15.
The simple example fails with

Invariant Violation
ReactFinalFormFieldArray(4.2.0)(undefined).render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

What is the expected behavior?

It works

Sandbox Link

https://codesandbox.io/s/olq4xrrz05

What's your environment?

"react-final-form-arrays": "1.0.3",
"react-final-form": "3.1.0",
"react-dom": "15.6.2",
"react": "15.6.2",
"final-form-arrays": "1.0.4",
"final-form": "4.2.0"

Update mutator is not documented

Are you submitting a bug report or a feature request?

bug report

What is the current behavior?

final-form-arrays provides update method but it's not documented in react-final-form-arrays.

What is the expected behavior?

All methods provided by final-form-arrays are listed here in the documentation.

Sandbox Link

n/a

What's your environment?

n/a

Other information

Link to the update method https://github.com/final-form/final-form-arrays#formmutatorsupdatename-string-index-number-value-any--void

Typescript error for FieldArrayProps

Are you submitting a bug report or a feature request?

bug report

What is the current behavior?

FieldArrayProps is included from final-form and throws an error

/node_modules/final-form/dist/index has no exported member 'FieldArrayProps'  

import { FieldArrayProps } from 'final-form'

What is the expected behavior?

Should not throw Typescript exception, but it looks like FieldArrayProps does not exist in https://github.com/final-form/final-form/blob/master/src/index.d.ts

onSubmit ARRAY_ERROR does not bubble to FieldArrayRenderProps

Are you submitting a bug report or a feature request?

Bug

What is the current behavior?

https://codesandbox.io/s/46ozq77v7

Type "test" or "fail" in Company, then submit

What is the expected behavior?

errors.customers[ARRAY_ERROR] is available somewhere in render props

Note: these props do get flagged

"invalid": true,
"submitFailed": true,

However I dont see

"submitError": [],

And an error prop seems to be missing

Extra

Code Sandbox has deps lists as 4.4.0
However in render props I see, not sure whats going on there

"__versions": {
    "final-form": "4.3.1",
    "react-final-form": "3.1.5"
  }

1.0.1 release not able to find ?

trying to do yarn install of 1.0.1 it says it cannot find.. Did this release happen properly or is busted like final-form releases ?

Upgrade react-final-form to v5: Remove use of `WithReactFinalForm`

Are you submitting a bug report or a feature request?

Feature Request: Upgrade react-final-form to v5.

Deprecated in v5

The previously exported withReactFinalForm HOC has been removed. Now you should use the useForm() hook if you'd like to get the 🏁 Final Form instance out of the context.

What is the current behavior?

react-final-form-arrays cannot be used with v5 of react-final-form. Must downgrade to v4 until library is updated.

What is the expected behavior?

Ability to use react-final-form-arrays with upgrade to new v5 react-final-form library.

Sandbox Link

What's your environment?

n/a - for all environments

Other information

Breaking change would mean react-final-form-array also needs a breaking change version bump.

Field.move keeps reference to old position

Bug

when moving a field in a array from position 0 to lets say position 2 and then type in the input on position 2, the value of the input in position 0 will be updated instead of active input on position 2.

What is the expected behavior?

To update the value of the current active input

Sandbox Link

https://codesandbox.io/s/oo367849lq

What's your environment?

"dependencies": {
    "styled-components": "2.2.4",
    "react-final-form-arrays": "2.0.1",
    "react-final-form": "4.0.1",
    "react-dom": "16.6.3",
    "react": "16.6.3",
    "final-form-arrays": "1.1.0",
    "final-form": "4.11.0"
  }

Remove empty item?

Field component has the parse prop that allows authors to change the value before storage. That being said, FieldArray does not have the same prop and makes it difficult to parse out empty items. This will need to be done after submitting which is not ideal.

Thoughts or ideas?

All Fields become dirty when unshifting if initialValues are present

Are you submitting a bug report or a feature request?

I think it's a bug (but might be simply a wrong behavior from my point of view)

What is the current behavior?

All the already existing values (fields) within the FieldArray become dirty when we add a value to the beginning of the array (with unshift or insert functions). It does occur only in case of an initialValues prop is provided to the Form component. If no initialValues is provided, adding a new value does not set the already existing ones as dirty.

Furthermore, this does not occur if adding a value at the end of the array.

What is the expected behavior?

Whatever method we use (push, unshift, insert) and to whatever index of the array we add the new value, the dirty state of the existing values should stay the same. The new value should not be dirty.

Sandbox Link

I used the 'Simple Example' from the doc and simply added a borderColor: orange style to the input if dirty.

  • Example with initialValues (just click on "Add customer" button) -> new value and existing ones become dirty: https://codesandbox.io/s/q1367y759. If you add multiple values, it becomes even more inconsistent.

  • Same example but without initialValues (works fine): https://codesandbox.io/s/1rw4o33r37

  • With initialValues but now using the push method. If you add a value without removing anything, the new value is not dirty. But if first you remove a value (by clicking on "Remove Customer" button) and then click on "Add Customer" button, the new value is dirty: https://codesandbox.io/s/k9n9l1l1o5

What's your environment?

Same as in the example.

Other information

If it's indeed something to should be fixed, I would be happy to help out (but will certainly need some guidance).

Thanks for the amazing work 😍

<FieldArray> re-renders when it shouldn't

Bug report

<FieldArray> gets re-rendered whenever anything in the form changes, not just the array and its contents.

What is the expected behavior?

It should work like a regular <Field>. That is, only subscribe to changes in the array (and still ignore contents of the array, apart from item additions/removals/reorders.

Sandbox Link

See https://codesandbox.io/s/yklq254pr1. Open console, add one customer and start editing company name. The whole array will be re-rendered on each key press, as indicate by messages in the console.

What's your environment?

"final-form": "4.5.2",
"final-form-arrays": "1.0.4",
"react-final-form": "3.3.1",
"react-final-form-arrays": "1.0.4",

Significant performance degradation when using react-final-form-arrays

I have a lot of forms in expansion panel and all of them have arrays in them. I am seeing significant performance impact . On further investigation looks like Chrome performance timeline tool is pointing towards react-final-form-arrays.es.js:289 which is significantly slowing down user experience . From the time user clicks and the changes show up on screen is a lot.

@erikras Do you have any thoughts on how I can improve the experience.

focus last after fields.push() not possible, because no possibility to focus on callback

Hello, I have 1 suggestion, when I push value, can't focus new element, because it is not created yet

                 fields.push({id: '', name: '', lastName: ''})
                 setTimeout(()=>{
                   form.focus(`persons[${fields.value.length}].id`)
                 },200)

this is how it works now, but obviously, its really bad solution, if fields.push had a callback, it would be nice

just wondering, why fields.push acts like async?

Question : How update a line

Is there a way to update the value of a line ?

Now I'm using :

let guestCopy = fields.value[index];
guestCopy.bookingOwner = true;

fields.remove(index);
fields.insert(index, guestCopy);

But it's a little bit dirty

TypeError Cannot read property 'changeValue' of undefined

First off, thanks so much for all of the amazing work you have done with React Final Form (as well as its predecessors).

This is a potential bug report

What is the current behavior?

I have an interesting issue where I have abstracted some of the React Final Form (RFF) logic into a higher-order-component called withFormHandler that wraps other components that are just the form inputs. Data handling (loading, processing submissions and resets) and form presentation (such as in a modal window) is controlled by the component that loads the form. This allows me to reuse all of my RFF boilerplate code with multiple forms.

One of these forms needs to dynamically create new rows of inputs for adding price modifiers (surcharges, discounts, taxes, etc) to a product, and I was looking to use React Final Form Arrays to do so, much like the how the simple example adds customers when you click a button. But because I don't require FieldArrays in every form, they are not loaded as part of the boilerplate, and are instead passed through from the parent component.

The actual problem is that when I attempt to use the mutators.push function, I receive the following error:

TypeError Cannot read property 'changeValue' of undefined

I have recreated a stripped down version of my setup in a sandbox: https://codesandbox.io/s/nn6jj4nj3p

If you look at the console output, you will see that the mutators appear to be getting passed through to my form, and the error is occurring because _ref2 in the push function is undefined:

var push = function push(_ref, state, _ref2) {
  var name = _ref[0],
      value = _ref[1];
  var changeValue = _ref2.changeValue; // <== this line go boom
  changeValue(state, name, function (array) {
    return array ? [].concat(array, [value]) : [value];
  });
};

So I don't know if the error is happening because of something I have set up incorrectly, or because this is an actual bug.

What is the expected behavior?

for mutators.push to not throw an error.

Sandbox Link

https://codesandbox.io/s/nn6jj4nj3p

What's your environment?

Local:
"react": "^16.6.0",
"react-dom": "^16.6.0",
"final-form": "^4.11.0",
"final-form-arrays": "^1.1.2",
"react-final-form": "^4.0.2",
"react-final-form-arrays": "^2.0.1",
OS: Windows 10
Browser: Chrome, FF
Node: 10.15.1

Other information

Thanks in advance for any and all help with regards to this issue

Typings for meta.error

Are you submitting a bug report or a feature request?

Bug

What is the current behavior?

They typescript typings for the meta object currently list error as a boolean, but the docs suggest it should be any to match the final-form version. It looks like initial and submitError are also booleans as well.

I'm not sure if this is intended as I've only just started using the library, but from the examples it doesn't look like it should be a boolean. Sorry if I've made a mistake.

What is the expected behavior?

The type should probably be any.

Use with calculation decorator

Are you submitting a bug report or a feature request?

bug report

What is the current behavior?

If remove array item other items will be changed

What is the expected behavior?

Other items should not be changed

Sandbox Link

https://codesandbox.io/s/7z85xxz8mx
try to remove the first row

What's your environment?

"final-form": "4.7.3",
"final-form-arrays": "1.0.4",
"final-form-calculate": "1.2.0",
"react": "16.4.0",
"react-dom": "16.4.0",
"react-final-form": "3.5.1",
"react-final-form-arrays": "1.0.4",

`dirtySinceLastSubmit` doesn't update when fields push/remove

Are you submitting a bug report or a feature request?

Bug report

What is the current behavior?

meta.dirtySinceLastSubmit is not updated after fields.push or fields.remove call. Though not tested yet, I doubt the same problem exists in other fields methods.

What is the expected behavior?

(See sandbox link)

  1. click "Submit" button
  2. click "Add a habit" button

Expect the habits field array to have meta.dirtySinceLastSubmit === true

Sandbox Link

https://codesandbox.io/s/upbeat-pine-23rt4

What's your environment?

Other information

FieldArray becomes permanently dirty on change

Are you submitting a bug report or a feature request?

Bug

What is the current behavior?

If I change any field in a FieldArray, the state of the parent FieldArray changes to dirty and stays dirty even after reverting to the original state.

What is the expected behavior?

The top level FieldArray should revert to pristine state if the fields are returned to their original state.

Sandbox Link

I'd be happy to provide one if needed.

What's your environment?

  • final-form: 4.9.1
  • react-final-form: 3.6.5
  • final-form-arrays: 1.1.0
  • react-final-form-arrays: 1.0.6
  • React: 16.4.1

Other information

https://github.com/final-form/react-final-form-arrays/blob/master/src/FieldArray.js#L78

Looking at where the FieldArray is registered, I see there is no equality comparator passed which would mean it defaults to a === check which would fail for an array.

I added a small snippet to enable addition of custom field level comparator to compare the arrays in my fork here: https://github.com/anant-singh/react-final-form-arrays/blob/dirty-field-check/src/FieldArray.js#L69-L88

Performance: Single change triggers complete form rerender.

Are you submitting a bug report or a feature request?

Its an observation that some performance relevant behaviour has changed between the documentation sandbox example and current library versions.

What is the current behavior?

Whenever one row of the array is modified, the whole form is rerendered.
Example: https://p41myp2q.codesandbox.io/
This is a fork of the official example, but with updated dependencies.

This can easily be observed when activating highlight updates in the React chrome extension
image

What is the expected behavior?

Only the relevant row should be rerendered and not trigger a rerender for all fields.
Example: https://kx8qv67nk5.codesandbox.io/

Sandbox Link

New dependencies, where the whole Form is rerendered: https://p41myp2q.codesandbox.io/
Original Example from documentation, where only the modified row is updated: https://kx8qv67nk5.codesandbox.io/

Update I tested this with different versions

  • Downgrading react-final-form-array and final-form-array to 1.0.0 does not change this behaviour
  • Downgrading final-form to 3.1.0 and react-final-form to 2.2 does fix the problem

--> Maybe this behaviour was introduced by Final Form 4.x or react final foem 3.x

When using "push" and then "remove" the form stays dirty.

Are you submitting a bug report or a feature request?

I believe this is a bug, but it is possible that I am not understanding something.

What is the current behavior?

When using a FieldArray, push, and remove you can end up with a dirty form, when I don't think it should be dirty.

I forked the Simple Demo: https://codesandbox.io/s/32p402x3om

  • Click Add Customer
  • Click the X to remove the just added field.

The form stays dirty, but I would expect it to be back to pristine.

What is the expected behavior?

  • I think the form should not be dirty, since you have undone the adding of a field (similar to typing in a text input, and then deleting the text)

Sandbox Link

https://codesandbox.io/s/32p402x3om

What's your environment?

React Final form. Mac OSX Chrome.

Other information

Thank you for a great library. Let me know if I can provide more information.

Keep consistency in example, TL;DR use id as key instead of name

Are you submitting a bug report or a feature request?

I'd like to have an example using id as key instead of name, to prevent an error to display close to the wrong field for instance.

What is the current behavior?

The basic array example is working fine because there is no validation, but if we add validation to this form, it would be buggy as we use "name" as key prop in the loop.

What is the expected behavior?

We should probaly add a more real worl example with validation and then use a generated id (like Math.random.toString())

Sandbox Link

What's your environment?

Other information

Thank you @erikras

Submit errors are not removed on `fields.remove` call

Are you submitting a bug report or a feature request?

A bug.

What is the current behavior?

Edit 🏁 React Final Form - Array Fields Submit error bug

What is the expected behavior?

Submit error is matched with array field - when the field is removed, submit error is also removed

What's your environment?

Forked from offical example:

"dependencies": {
    "styled-components": "2.2.4",
    "react-final-form-arrays": "1.0.0",
    "react-final-form": "1.1.1",
    "react-dom": "16.2.0",
    "react": "16.2.0",
    "final-form-arrays": "1.0.0",
    "final-form": "1.2.1"
  }

Locally:

    "final-form": "^4.1.0",
    "final-form-arrays": "^1.0.4",
    ...
    "react-final-form": "^3.0.5",
    "react-final-form-arrays": "^1.0.3",

Validate errors on field arrays

Follow discussion here: #3 (comment)

Edit RFF Field Array Problem

When mixed field with field arrays, the form cannot submit due to errors object can never be empty ie.

Form errors:
{
  "customers": [
    {}
  ]
}

I understand the reason for field arrays keys here, but I have to write workarounds such as:

onSubmit = () => {
  this.formEl.dispatchEvent(new Event('submit')); // trigger final-form submit
  this.submit(); // check if "errors.customers" array is full of empty object and submit
}

Just an idea - could we expose validation function (the function which checks for form errors then execute props.onSubmit()) to make it more flexible for this usecase?

FieldArray's unshift mutator does not update state correctly

Are you submitting a bug report or a feature request?

Bug

What is the current behavior?

When using the unshift mutator to add an item to the beginning of an array, the touched state from the item previously at index zero (if one exists) is maintained.

What is the expected behavior?

I would expect the item that was added to the beginning of the array to have a touched state of false.

Sandbox Link

N/A, but I will happily provide one if needed.

What's your environment?

  • final-form: 4.8.3
  • react-final-form: 3.6.4
  • final-forms-array: 1.0.4
  • react-final-forms-array: 1.0.6
  • React: 16.4.1
  • Chrome: 68.0.3440.75

Other information

N/A

using decorators/final form calculate with form array

👋 Hey, thanks for taking an interest in making 🏁 React Final Form Arrays!
After trying other form library i can definitely conclude It is near perfect library for forms, just some edges to be sorted out.

Are you submitting a bug report or a feature request?

feature request or maybe a bug report

What is the current behavior?

There is no specification on how to use final-form-calculate or more specifically decorators with array-form

What is the expected behavior?

exposing decorator api to for array form

Sandbox Link

n/a

What's your environment?

applicable to all versions

Other information

n/a

Try to move Fields with Conditions not working

Are you submitting a bug report or a feature request?

Bug report

What is the current behavior?

When I try to Drag and Drop group of Fields with conditions to be displayed or not in a FieldArray, there is an error happening: "Cannot read property 'active' of undefined"

If you try to reproduce it from the sandbox linked below:

  1. Create several customers
  2. Enter on one of them "test" to validate the condition to display the lastName
  3. Try to Drag and Drop a customer with the handler on the left "::"
  4. The error come here 🔴

What is the expected behavior?

The expected behavior is to be able to move Fields that have Conditions Fields inside

Sandbox Link

Edit 🏁 React Final Form - Field Arrays

Extend from React.Component (instead of React.PureComponent)

Are you submitting a bug report or a feature request?

Eh, this feels kind of somewhere in the middle.

What is the current behavior?

FieldArray extends React.PureComponent.

What is the expected behavior?

FieldArray extends React.Component.

Sandbox Link

N/A

What's your environment?

N/A

Other information

For the reasons discussed in final-form/react-final-form#150, I'd like to see parity across all react-final-form* packages.

The tl,dr: I have external state I feed into my FieldArray render component. I also have to explicitly pass this state to FieldArray as a prop, so the component re-renders.

isEqual returns true by default

image

@erikras
This function is used to determine whether the fields are pristine or not, so if we have initial values and current form values - [] and [{...},{...}], it shows that the values are pristine.
Could you please clarify the reason why it returns true in case of no callback is provided? I think it would be better to write it in the docs because it's quite confusing, I have expected it working this way - 'return this.props.a === this.props.b' by default instead of returning true when the custom callback is not provided, thanks!.
'

Should the type of FieldArrayRenderProps['fields']['length'] be non-optional?

Currently FieldArrayRenderProps.fields gets length from FieldState where it is optional: length?: number. From the code, it looks like it is expected to always be a number. With it being optional you end up needing to do things like fields.length && fields.length > 1 if you want to see if there's more than one field. If you agree, I'd be happy to submit a PR

Add react-lifecycle-compat to external array in rollup config

Are you submitting a bug report or a feature request?

Bug report. (Debatably so).

What is the current behavior?

react-lifecycle-compat is inlined into the ES Module build. (Also the case for the commonjs build).

What is the expected behavior?

react-lifecycle-compat is imported via import or require (for the module build and commonjs builds, respectively).

What's your environment?

Latest React Final Forms Array, Final Form Arrays, and Final Form.

Other information

For reasons outlined in reactjs/react-lifecycles-compat#31, I'm using react-final-form-arrays with Preact, and I'm going to need to shim react-lifecycle-compat to something else. Difficult to do that when it is inlined :)

Calling .push() on click can result in too many fields added

Are you submitting a bug report or a feature request?

This is a bug report.

What is the current behavior?

I cannot limit how many entries the user can push into an array. For instance, adding a conditional clause to a button's onClick handler doesn't always work. The problem appears when there is a high CPU utilization and several clicks can be made before a render.

I created a sandbox that shows off the problem. However, to actually see the issue you would probably need to use CPU throttling. Also, you may need to click like crazy. 😄

What is the expected behavior?

There should be a way to consistently limit how many fields can be added.

Sandbox Link

https://codesandbox.io/s/2zjl0w9l3n

What's your environment?

Just the "standard" one, like in the sandbox.

Other information

I assume the cause of this problem is that .push() is asynchronous. So multiple calls will get queued and, on a system with limited CPU power, may get executed before the next render gets finished. And the value of fields.length is only updated after render.

I'm not sure what the solution could be. Maybe provide something like an .update() method, which could be used like so:

onClick={() => fields.update(fields => {
  if (fields.length < 5) {
    fields.push('foo');
  }
})}

I can see that this issue is probably very niche. But it makes me uneasy that my users might get invalid UI (and/or any bugs that might come from e.g. sending too many fields to an API) just because they're installing an update on their computer at the same time or something.

It's also really not straightforward to get around this. For instance, the API doesn't provide a .slice() method for when we want to display only X entries.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.