3

I'd like to do some responsive logic, where when a value changes it triggers other values to change in a form.

I'm using mantine forms, and so far the best approach I've been able to come upon is something like the following:

const onUserChange = (e) => {
   // form.values.acounts.user contains the previous user value
   // e contains the incoming update to it
   form.setFieldValue('other.property.associated.with.user', e);
 }

 <Select label="User"
              data={users}
              {...form.getInputProps(`accounts.user`)}
              onChange={(e) => {
                onUserChange(e);
                form.getInputProps(`accounts.user`).onChange(e)
              }}
      ></Select>

This approach 'seems' to be decent, but I'm not sure if there's a better way. Anyone come across this before? Maybe some neat callback syntax or something?

iamaword
  • 1,327
  • 8
  • 17

3 Answers3

2

Seems like a legitimate way to override the libraries onChange handler. However, I would use onChangeUser to also set the user's value:

const onUserChange = ({ target }) => {
  const { value } = target;
  form.setFieldValue('other.property.associated.with.user', fn(value)); // fn transforms the value for the associated property
  form.setFieldValue('accounts.user', value);
};

<Select label="User"
  data={users}
  {...form.getInputProps('accounts.user')}
  onChange={onUserChange}
></Select>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 1
    yeah that's effectively the flow I ended up taking. Sometimes I also had to wrangle in useEffect, since stetting the value is a state update – iamaword Feb 07 '23 at 16:01
1

I encountered similar situation. In my case I have to provide search-suggestions using. For that I have to set debouncedState on every change.

In your case I suggest add an extra if statement before calling onChange(e)

<Select label="User"
          data={users}
          {...form.getInputProps(`accounts.user`)}
          onChange={(e) => {
            onUserChange(e);
            if(form.getInputProps(`accounts.user`).onChange)
              form.getInputProps(`accounts.user`).onChange(e)
          }}
  ></Select>
0

It turns out the library doesn't do much magic in regards to the onchange, and effectively just sets the form value via form.setFieldValue. As long as the onchange provided sets the value you don't need to re-reference the onchange gotten from 'getInputProps'

iamaword
  • 1,327
  • 8
  • 17