Why I can't change the value in this nested object using formik

Viewed 29

I got a schema like this

const pSchema = object().shape({
  text: object().shape({
    shortName: string().required(),
    longName: string(),
    description: string(),
    welcomeMessage: string()
  }),
  config: object().shape({
    region: string(),
    texts: object().shape({
      done: string(),
      title: string(),
      description: string()
    })
  })
});

As you can see there are some nested object in there.

What I am doing is I am using formik handleChange to handle the changes in the input form. But some of them are not working when nested deeply.Such as config.texts.done input field.

Since there are a lot of code I won't show them in here

Here is the link for codeSandBox https://codesandbox.io/s/formik-example-forked-6msipj?file=/index.js:305-656

1 Answers

You're adding "values.[fieldName]" in each Form.Item id you can't properly change.

The correct version should be this one:

<Form.Item label="Can't write Title">
  <Input
    id="config.texts.title"
    value={values.config.texts.title}
    onChange={handleChange}
    onBlur={handleBlur}
  />
</Form.Item>

<Form.Item label="Can't write Description">
  <Input
    id="config.texts.description"
    value={values.config.texts.description}
    onChange={handleChange}
    onBlur={handleBlur}
  />
</Form.Item>

<Form.Item
  wrapperCol={{
    sm: { offset: 0 },
    md: { offset: 0 },
    lg: { offset: 6 }
  }}
>
  <Space>
    <Button
      type="default"
      htmlType="button"
      shape="round"
      onClick={() => console.log(-1)}
    >
      Cancel
    </Button>

    <Button
      type="primary"
      htmlType="submit"
      shape="round"
      disabled={!isValid}
      data-cy="save-button"
    >
      Save
    </Button>
  </Space>
</Form.Item>

By replacing id="values.config.texts.description" with id="config.texts.description" everything should be working fine.

This is a codesandbox working: https://codesandbox.io/s/formik-example-forked-uc2hw1

Related