Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdown and value not updating in Formik + React Form

Following are the problems I am facing with my code -

  1. Commodity Dropdown is initialised incorrectly - I am expecting commodity 2 to be available on load time but it is taking commodity 1 RESOVLED initialValue={values.commodity.value} should be there in commodity Select.
  2. On change of commodity from commodity dropdown, plant dropdown is not updating at all. [STILL PENDING]

Working Example - https://codesandbox.io/s/ql95jvpxq4 (correct behaviour)

I tried to replicate the same with my Select but somehow its not working. Let me know what I am doing wrong here.

Faulty code - https://codesandbox.io/s/01qno3vmvl

Code -

const formikEnhancer = withFormik({
  mapPropsToValues: props => ({
    commodity: { value: "commodity2", label: "commodity2" },
    plant: { value: "Plant3", label: "Plant3" }
  }),
  handleSubmit: (values, { setSubmitting }) => {
    const payload = {
      ...values,
      commodity: values.commodity.value,
      plant: values.plant.value
    };
    setTimeout(() => {
      alert(JSON.stringify(payload, null, 2));
      setSubmitting(false);
    }, 1000);
  },
  displayName: "MyForm"
});

Form -

<form onSubmit={handleSubmit}>
        <div style={{ margin: "1rem 0" }}>
          <label htmlFor="commodity" style={{ display: "block" }}>
            Commodity
          </label>
          <Select
            id="commodity"
            name="commodity"
            value={commodities}
            initialValue={values.commodity}
            onChange={(field, value) => {
              console.log(value);
              setFieldValue("plant", plants[value][0]);
            }}
          />
        </div>
        <div style={{ margin: "1rem 0" }}>
          <label htmlFor="plant" style={{ display: "block" }}>
            Plant
          </label>
          <Select
            id="plant"
            name="plant"
            value={plants[values.commodity.value]}
            onChange={setFieldValue}
          />
        </div>

        <button
          type="button"
          className="outline"
          onClick={handleReset}
          disabled={!dirty || isSubmitting}
        >
          Reset
        </button>
        <button type="submit" disabled={isSubmitting}>
          Submit
        </button>

        <DisplayFormikState {...this.props} />
      </form>

FYI - I am new to formik so may be I am missing something very common here.

like image 978
swapnesh Avatar asked Oct 22 '25 06:10

swapnesh


1 Answers

The initialValue was wrong set up. It should be string value instead of object. Select value was changing using state and props of parent component.

Here is working variant https://codesandbox.io/embed/n102qqq0nl