I have an input form that I want to validate the input fields of once a 'search' button is clicked.
Most answers I have seen are having the input validated live, as the user enters it into the form.
I don't want to do this as some of the validation I need to do is a costly operation (validating an API key for example), therefore constantly checking it as it's entered is not an option.
This is also a serverless, single page application, and as far as I could tell - onSubmit would reload the page, so I'm not using that.
I have a simple form that looks similar to this:
const [formData, setFormData] = useState({});
.......
function handleFormChange(event) {
let data = formData;
data[event.target.name] = event.target.value;
setFormData(data);
}
........
<form id="search-form" >
<TextField name="apiKey" label="API Key" onChange={handleFormChange} defaultValue={formData.apiKey} />
<TextField name='itemName' label="Enter Item" onChange={handleFormChange} />
<Button name='search-button' onClick={validate} >Search</Button>
</form>
I can't work out what to put into validate() to either set the errors on the text fields or perform the search.
I've tried passing a function into the error prop that checks to see if an errors state variable is populated, I've tried looking into using refs to set the error state but I couldn't see any function that would set the error state.
The formData variable will hold the current data, so it's easy to check 'is this data valid' but for the life of me, I can't work out how to manually trigger the error state.
I'm using React hooks FYI