How to change the value of an object within the array with Formik and Yup?

Asked

Viewed 166 times

-1

Here I create the initial values of Shape:

const defaultFormShape = {
  name: '',
  email: '',
  group: { id: '' },
  addresses: [{
    name: ''
  ]}
};

And here I validate Schema:

const validationSchema = Yup.object().shape({
  name: Yup.string().required('Name is required.'),
  email: Yup.string().required('Email is required.'),
  group: Yup.object().shape({ 
    id: Yup.string().required('Group ID is required.')
  }).nullable(),
  addresses: Yup.array().of(
    Yup.object().shape({
      name: Yup.string().required('Addresses name is required.')
    }),
    Yup.object().shape({
      street: Yup.string().required('Addresses street is required.')
    })
  ).nullable()
});

what I need, is that when the user is in form editing mode, take the value that is coming from the API, display in the input and allow changing this value. So far so good, but I’m having trouble editing the value of the object name within the array. To try to do this in the input:

<TextField
  error={Boolean(touched.addresses && errors.addresses && errors.addresses.map(addressesName => addressesName.name) )}
  helperText={touched.addresses && errors.addresses && errors.addresses.map(addressesName => addressesName.name) }
  fullWidth
  label="Addresses Name"
  name='addressesName'
  onBlur={handleBlur}
  onChange={handleChange}
  value={Array.isArray(values.addresses) ? values.addresses.map(value => value.name) : values.addresses}
  variant="outlined"
/>

So, I need you to when the input changes, go to the Addresses array and edit the key value name

inserir a descrição da imagem aqui

  • why did they give -1? It would be simpler to post the doubt here and discuss.

1 answer

0

The problem was the name of the input, thus putting:

<TextField
  error={Boolean(touched.addresses && errors.addresses && errors.addresses.map(addressesName => addressesName.name))}
  helperText={touched.addresses && errors.addresses && errors.addresses.map(addressesName => addressesName.name)}
  fullWidth
  label="Addresses Name"
  name='addresses[0][name]' //aqui a resolução
  onBlur={handleBlur}
  onChange={handleChange}
  value={Array.isArray(values.addresses) ? values.addresses.map(value => value.name) : values.addresses}
  variant="outlined"
/>

which is what the API expects, worked out.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.