Following are the problems I am facing with my code -
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.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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With