I'm porting some of my forms I made using SUIR over to a Formik implementation. I have input components that need custom change handlers to perform actions. How can I pass my change handler to the onChange
prop so the values are tracked by formik?
I've tried something like this, but with no luck.
onChange={e => setFieldValue(dataSchemaName, e)}
which is mentioned in a different post here.
It's also mentioned here, but I can't quite get my custom change handler to hook up nicely with Formik.
My change handler looks like this
handleSchemaChange = (e, { value }) => {
this.setState({ dataSchemaName: value }, () => {
console.log("Chosen dataSchema ---> ", this.state.dataSchemaName);
//also send a request the selfUri of the selected dataSchema
});
const schema = this.state.dataschemas.find(schema => schema.name === value);
if (schema) {
axios
.get(schema.selfUri)
.then(response => {
console.log(response);
this.setState({
fields: response.data.data.fields,
});
console.log(this.state.fields);
})
.catch(error => console.log(error.response));
}
};
Here's an example of one of my form fields using a dropdown
<Form.Field>
<label style={{ display: "block" }}>
Select a Schema
</label>
<Dropdown
id="dataSchemaName"
multiple={false}
options={dataschemas.map(schema => {
return {
key: schema.id,
text: schema.name,
value: schema.name
};
})}
value={dataSchemaName}
onChange={this.handleSchemaChange}
/>
</Form.Field>
I have a sandbox with the issue
You can pass the setFieldValue
function to your function handleSchemaChange
and then use it inside.
So, instead of onChange={this.handleSchemaChange}
make it
onChange={(e, val) => this.handleSchemaChange(e, val, setFieldValue)}
.
And inside your handleSchemaChange
function:
handleSchemaChange = (e, { value }, setFieldValue) => {
setFieldValue('dataSchemaName', value);
... the rest of your implementation
}
Here is a sandbox with the solution implemented: https://codesandbox.io/s/formik-create-query-schema-uq35f
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