I can't seem to update my state with useState(), whenever my alert displays, I always see my state displaying its initial value.
Sample code below, my expectation is that when I click the Save button, setData will update data with new values I have in my form, then display contents of data with alert. However, what's happening is that whenever I click Save, alert is always displaying my initial values.
How do I update data with my field values so that my alert can pick up the changes?
const initialValues = {
title: "",
description: ""
}
const CreateForm = (props) => {
const [data, setData] = useState(initialValues);
const handleSave = (values) => {
setData({
title: values.title,
description: values.description
});
setTimeout(() => {
alert(JSON.stringify(data, null, 2));
}, 3000)
}
return (
<div>
<Formik initialValues={data}
validationSchema={validationSchema}
onSubmit={(values) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
}, 3000)
}}
>
{props => (
<Form>
<TextField name="title" type="input" label="Title" />
<TextField name="description" type="input" label="description" />
<div >
<Button type="submit" variant="contained" color="primary">Submit</Button>
<Button variant="contained" color="secondary" onClick={() => handleSave(props.values)}>Save</Button>
</div>
</Form>
)}
</Formik>
</div>
)
}
export default CreateForm