final-form / final-form/react-final-form-listeners
How to avoid looping if two fields change each other's values?
- Dominant language
- TypeScript
- Stars
- 95
- Forks
- 21
- PR merge metrics
- No merged PRs in 30d
Description
I need to change the value of the **give field** if the value of the **resave field** changes and vice versa.
here is an example of my code:
```javascript
import React from 'react';
import { Form, Field } from 'react-final-form';
import { OnChange } from 'react-final-form-listeners';
import RenderField from '../../components/Forms/FieldRender';
import FieldBtns from '../../components/Forms/FieldBtns';
// import AutoSave from '../../components/Forms/AutoSave';
const WhenFieldChanges = ({
field,
becomes,
set,
to,
}) => (
{(
// No subscription. We only use Field to get to the change function
{ input: { onChange } },
) => (
{() => {
if (becomes) {
onChange(to);
}
}}
)}
);
let prevGiveCurrency;
let prevReceiveCurrency;
let prevGive;
let prevReceive;
const ExchangeForm = ({
onSubmit,
pairs,
exchangeSetFrom,
exchangeSetTo,
price,
}) => (
{
// const errors = {};
// return errors;
// }}
render={({
handleSubmit,
submitting,
values,
}) => {
prevGive = values.give;
prevReceive = values.receive;
if (prevGiveCurrency !== values.giveCurrency) {
exchangeSetFrom(values.giveCurrency);
}
prevGiveCurrency = values.giveCurrency;
if (prevReceiveCurrency !== values.receiveCurrency) {
exchangeSetTo(values.receiveCurrency);
}
prevReceiveCurrency = values.receiveCurrency;
return (
{/* */}
I give
{pairs.map(pair => (
{pair.fromSymbol}
))}
I receive
{pairs.find(e => e.fromSymbol === values.giveCurrency)
&& pairs.find(e => e.fromSymbol === values.giveCurrency).toSymbols.map(symbol => (
{symbol}
))}
{JSON.stringify(values, 0, 2)}
);
}}
/>
);
export default ExchangeForm;
```
Contributor guide
Assessment
This issue has not been assessed yet.