Reputation: 158
I'm using Formik and Yup in react, when I click submit button and the onSubmit event firing, And inside of the event the fetch function called twice,
import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import Container from '@material-ui/core/Container';
import { TextField } from 'formik-material-ui';
import { Formik, Field, Form } from 'formik';
import * as Yup from 'yup';
class LoginForm extends Component {
constructor(props) {
super(props);
this.state = {classes: this.props.classes, isLoading: false }
}
render() {
return (
<Formik
initialValues={initialFormValues}
validationSchema={validationFrom}
onSubmit={(values, actions) => {
this.setState({ isLoading: true });
console.log(values);
actions.setSubmitting(false);
console.log('SUCCESS!! :-)\n\n' + JSON.stringify(values, null, 2));
fetch('http://xx.xx.xx.xx.compute-1.amazonaws.com:9000/api/v1/userAuth', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(values)
})
.then(Response => {
console.log(Response);
this.setState({ isLoading: false });
})
}
}
render={({ submitForm, isSubmitting, isValid }) => (
<Form>
<Container component="main" maxWidth="xs" >
<div className={this.state.classes.paper}>
<Field
variant="outlined" margin="normal" fullWidth label="User ID" name="userid" id="userid" type="text"
autoComplete="userid" component={TextField} />
<Field
variant="outlined" margin="normal" fullWidth id="password" name="password" label="Password" type="password"
autoComplete="current-password" component={TextField} />
<Button
type="submit" fullWidth variant="contained" color="primary"
className={this.state.classes.submit} disabled={isSubmitting || !isValid}
> Sign In
</Button>
</div>
</Container>
</Form>
)}
/>
)
}
}
export default LoginForm;
I'm new to React, I have google it but no luck, Here is my tried code, I called the API for user Authentication to verify userId and password, Please suggest me to do correct way to call API.
Upvotes: 4
Views: 4003
Reputation: 15821
I see that the first call is 0 bytes.
Although I cannot see the detail of your XHR call, IMHO the first call is not a POST verb but an OPTION, as you are probably doing a network request to a backend domain that is different from the domain where React app is served from.
In OPTION call the server authorizes or deny the access to an endpoint on the basis of CORS. So, nothing strange, in my opinion.
Upvotes: 5