0

I'm starting with react.

I would like the value returned from 'handleClickLoadPIX' to be filled as the value of field 'pj_pix_key'.

I tried to use value={pj_pix_key} on the <OutlinedInput but returned value is never possible to be deleted to the field

//** Const

const defaultFields = {
  financial: {
    fields: {
      init: {
        pj_pix_key: ``,
      },
      reset: {
        pj_pix_key: ``,
      }
    },
    schema: yup.object().shape({
    pj_pix_key: yup.string().optional(),
    })
  }
}

// ** States

const [pj_pix_key, setPj_pix_key] = React.useState('')

// ** Handle

const handleClickLoadPIX = async value => {
    let lookupFieldValue = 'returned-key-from-endpoint'
    
    setPj_pix_key('load-key-from-endpoint')
}

// ** Hooks

const {
    reset: financialReset,
    control: financialControl,
    handleSubmit: handleFinancialSubmit,
    formState: { errors: financialErrors }
} = useForm({
    defaultValues: defaultFields.financial.fields.init,
    mode: 'onBlur',
    resolver: yupResolver(defaultFields.financial.schema)
})

//** JSX

<FormControl fullWidth>
  <InputLabel id='pj_pix_key-label' htmlFor='pj_pix_key' error={Boolean(financialErrors.pj_pix_key)}>
    Chave PIX
  </InputLabel>
  <Controller
    name='pj_pix_key'
    control={financialControl}
    rules={{ required: false }}
    render={({ field: { value, onChange, onBlur } }) => (
      <OutlinedInput
        value={value}
        label='Chave PIX'
        onChange={onChange}
        onBlur={onBlur}
        id='pj_pix_key'
        error={Boolean(financialErrors.pj_pix_key)}
        type='text'
        placeholder='ex.: 12345678'
        aria-describedby='pj_pix_key-helper'
        labelId='pj_pix_key-label'
        endAdornment={
          <InputAdornment position='end'>
            <Tooltip title='Carregar PIX do CNPJ ou Email comercial'>
              <IconButton
                edge='end'
                onClick={e => handleClickLoadPIX()}
                onMouseDown={e => e.preventDefault()}
                aria-label='pj_pix_key-helper'
              >
                <Icon icon='mdi:auto-download' />
              </IconButton>
            </Tooltip>
          </InputAdornment>
        }
      />
    )}
  />
  {financialErrors.pj_pix_key && (
    <FormHelperText sx={{ color: 'error.main' }} id='pj_pix_key-helper'>
      Campo obrigatório
    </FormHelperText>
  )}
</FormControl>
Diego
  • 31
  • 3

1 Answers1

-1

The issue you're facing is likely due to how you're managing the state of the pj_pix_key field. You're using both React Hook Form's Controller and a separate React state (pj_pix_key) to manage the value of the field, which can lead to conflicts.

Try these steps:

1. Use setValue from React Hook Form to Update the Field Value

React Hook Form provides a setValue function that you can use to programmatically set the value of a field. This way, you don't need to maintain a separate state (pj_pix_key) for the field.

First, destructure setValue from the useForm hook:

const {
  reset: financialReset,
  control: financialControl,
  handleSubmit: handleFinancialSubmit,
  setValue, // <-- Add this
  formState: { errors: financialErrors }
} = useForm({
  defaultValues: defaultFields.financial.fields.init,
  mode: 'onBlur',
  resolver: yupResolver(defaultFields.financial.schema)
});

2. Update handleClickLoadPIX to Use setValue

const handleClickLoadPIX = async value => {
  let lookupFieldValue = 'returned-key-from-endpoint';
  setValue('pj_pix_key', lookupFieldValue); // <-- Use setValue here
};

3. Remove the Separate State for pj_pix_key

Since you're using React Hook Form to manage the form state, you don't need a separate React state for pj_pix_key. You can remove the following line:

const [pj_pix_key, setPj_pix_key] = React.useState('');

Your JSX code for the Controller and OutlinedInput should work as is. Just make sure you're not using the separate state (pj_pix_key) anywhere in your JSX. Try this updates and inporate them into code. This should allow clicking the button should set the value of pj_pix_key to the returned key, and you should also be able to manually delete or change the value.

jimmykurian
  • 301
  • 2
  • 12