final-form / final-form/react-final-form-arrays
Calling .push() on click can result in too many fields added
- Dominant language
- TypeScript
- Stars
- 210
- Forks
- 69
- PR merge metrics
- No merged PRs in 30d
Description
### 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](https://umaar.com/dev-tips/88-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.
Contributor guide
Assessment
This issue has not been assessed yet.