I have the following sample code which makes an api call when a form is submitted. How do I wait for 'apiResult' to be set before assigning value1 and value2?
I thought 'awaiting' axios would do this, but React is telling me it can't read the property 'field1' of null, as it's obviously trying to set the two values before either the data has been returned from the api call or before React has set the state (setApiResult).
What's the correct way to do this, please? Ideally, I only want to make one api call per form submission.
const Example = () => {
const [state, setState] = useState()
const [apiResult, setApiResult] = useState(null)
async function handleSubmit() {
const apiData = await axios(
`https://someapiurl.com/apiquery=${state}`
)
setApiResult(apiData)
const value1 = apiResult.field1.data;
const value2 = apiResult.field2.data;
// ... DO SOMETHING WITH VALUE1, VALUE2
}
return (
<form onSumbit={handleSubmit}>
<input
onChange={(e) => setState(e.target.value)}
type="text" />
</form>
)
}
Any help very much appreciated, Matt.