I used formik and yup for validating my form with list and create a data in my database…i used state to store my input values… but while validating using formik functions..handlechange,values,error,handlesubmit..the data gets stored in values
of the formik’s function values…how can i make the onchange event to store my data in the state to make my code to create and store the data in database..
import './App.css';
import { Formik } from "formik";
import * as Yup from "yup";
import { API, graphqlOperation } from 'aws-amplify'
import { listRestaurants } from './graphql/queries'
import { createRestaurant } from './graphql/mutations'
class App extends Component {
state = { Name: '', Email: '', Location: '', restaurants: [] }
async componentDidMount() {
try {
const apiData = await API.graphql(graphqlOperation(listRestaurants))
const restaurants = apiData.data.listRestaurants.items
this.setState({ restaurants })
} catch (err) {
console.log('error: ', err)
}
}
onChange = e => {
this.setState({ [e.target.name]: e.target.value })
}
createRestaurant = async () => {
const { Name, Email, Location } = this.state
if (Name === '' || Email === '' || Location === '') return
try {
const restaurant = { Name, Email, Location }
const restaurants = [...this.state.restaurants, restaurant]
this.setState({ restaurants, Name: '', Email: '', Location: '' })
await API.graphql(graphqlOperation(createRestaurant, {input: restaurant}))
console.log('Data successfully created!')
} catch (err) {
console.log('error: ', err)
}
}
render() {
return (
<Formik
initialValues={this.state}
validationSchema={validationSchema}
onSubmit={values => {
console.log(values);
}}
>
{
({ handleSubmit, handleChange, values, errors }) =>
(
<form className="App" onSubmit={handleSubmit}>
<div style={styles.inputContainer}>
<input
name='Name'
placeholder='Name'
onChange={handleChange}
value={values.Name}
//value={this.state.Name}
style={styles.input}
/>
{errors.Name}
<input
name='Email'
placeholder='Email'
onChange={handleChange}
//onChange={this.onChange}
value={values.Email}
//value={this.state.Email}
style={styles.input}
/>
{errors.Email}
<select name="Location" onChange={this.onChange} value={this.state.Location} style={styles.select} required>
<option>Select Your Country /</option>
<option value="India">India</option>
<option value="Australia">Australia</option>
<option value="America">America</option>
<option value="Canada">Canada</option>
<option value="Dubai">Dubai</option>
<option value="Russia">Russia</option>
</select>
</div>
<button
type='submit'
style={styles.button}
onClick={this.createRestaurant}
>Create</button>
{
this.state.restaurants.map((rest, i) => (
<div key={i} style={styles.item}>
<p style={styles.Name}>{rest.Name}</p>
<p style={styles.Email}>{rest.Email}</p>
<p style={styles.Location}>{rest.Location}</p>
</div>
))
}
</form>
)}
</Formik>)
}
}```