В настоящее время я заканчиваю работу с системой MERN и заметил эту очень странную ошибку: когда я нажимаю кнопку Отправить на странице реакции, пользователь сохраняется в Mongo db, чуть позже другой пользователь сохраняется с теми же данными.Вот мой код (интерфейс React)
import React from "react";
import withStyles from "@material-ui/core/styles/withStyles";
import InputLabel from "@material-ui/core/InputLabel";
// core components
import GridItem from "components/Grid/GridItem.jsx";
import GridContainer from "components/Grid/GridContainer.jsx";
import CustomInput from "components/CustomInput/CustomInput.jsx";
import Button from "components/CustomButtons/Button.jsx";
import Card from "components/Card/Card.jsx";
import CardHeader from "components/Card/CardHeader.jsx";
import CardAvatar from "components/Card/CardAvatar.jsx";
import CardBody from "components/Card/CardBody.jsx";
import CardFooter from "components/Card/CardFooter.jsx";
import axios from 'axios';
import avatar from "assets/img/faces/marc.jpg";
import Styles from './Styles'
import { Form, Field } from 'react-final-form'
const styles = {
cardCategoryWhite: {
color: "rgba(255,255,255,.62)",
margin: "0",
fontSize: "14px",
marginTop: "0",
marginBottom: "0"
},
cardTitleWhite: {
color: "#FFFFFF",
marginTop: "0px",
minHeight: "auto",
fontWeight: "300",
fontFamily: "'Roboto', 'Helvetica', 'Arial', sans-serif",
marginBottom: "3px",
textDecoration: "none"
}
};
class UserProfile extends React.Component {
onChange = (e) => {
/*
Because we named the inputs to match their
corresponding values in state, it's
super easy to update the state
*/
this.setState({ [e.target.name]: e.target.value });
console.log('data', this.state.name)
}
onSubmit = async (values , e) => {
alert('User Created ')
let data = values;
axios.post('/api/users/newuser', {data})
.then(result => console.log(result))
.catch(err => console.log(err))
}
state = {
id: '',
name: "",
address:"",
phonenumber: "",
isp: "",
account: "",
accounttype: "",
paid: '',
staticip:'',
staticipdate: Date,
bill: '',
balance: '',
username: '',
pass: '',
apip: ''
render(){
return <div>
<code><h1>Create New User</h1>
<h3>Unlimitik POS system V1.0</h3>
<Form
onSubmit={this.onSubmit}
initialValues={{ }}
render={({ handleSubmit, form, submitting, pristine, values }) => (
<form onSubmit={handleSubmit}>
<div>
<label>Full Name</label>
<Field
name="name"
component="input"
type="text"
placeholder="Full Name"
/>
</div>
<div>
<label>Address</label>
<Field
name="address"
component="input"
type="text"
placeholder="address"
/>
</div>
<div>
<label>Phone Number</label>
<Field
name="phonenumber"
component="input"
type="text"
placeholder="phonenumber"
/>
</div>
<div>
<label>ISP</label>
<Field
name="isp"
component="input"
type="text"
placeholder="isp"
/>
</div>
<div>
<label>Account</label>
<Field
name="account"
component="input"
type="text"
placeholder="account"
/>
</div>
<div>
<label>Account Type</label>
<Field
name="accounttype"
component="input"
type="text"
placeholder="accounttype"
/>
</div>
<div>
<label>Paid</label>
<Field
name="paid"
component="input"
type="text"
placeholder="paid"
/>
</div>
<div>
<label>Static IP</label>
<Field
name="staticip"
component="input"
type="text"
placeholder="staticip"
/>
</div>
<div>
<label>Static IP Date</label>
<Field
name="staticipdate"
component="input"
type="date"
placeholder="staticipdate"
/>
</div>
<div>
<label>Bill</label>
<Field
name="bill"
component="input"
type="text"
placeholder="bill"
/>
</div>
<div>
<label>Balance</label>
<Field
name="balance"
component="input"
type="text"
placeholder="balance"
/>
</div>
<div>
<label>username</label>
<Field
name="username"
component="input"
type="text"
placeholder="username"
/>
</div>
<div>
<label>pass</label>
<Field
name="pass"
component="input"
type="text"
placeholder="pass"
/>
</div>
<div>
<label>AP / IP</label>
<Field
name="apip"
component="input"
type="text"
placeholder="AP / IP"
/>
</div>
<div>
<label>Notes</label>
<Field name="notes" component="textarea" placeholder="Notes" />
</div>
<div className="buttons">
<button type="submit" disabled={submitting || pristine} >
Submit
</button>
<button
type="button"
onClick={form.reset}
>
Reset
</button>
</div>
<pre>{JSON.stringify(values, 0, 2)}
)} />
экспорт по умолчанию UserProfile;
Происходит то, что запрос сохраняется в mongodb через 2 или 3 секунды (без точного времени), другой запрос отправляется, а документ сохраняется 2 раза.вот маршрут express.js
router.post('/newuser', async (req, res) => {
var x = Math.floor(Math.random() * Date.now() * 0.000000002);
const data = new User ({
id: x,
name: req.body.data.name,
address: req.body.data.address,
phonenumber: req.body.data.phonenumber,
isp: req.body.data.isp,
account: req.body.data.account,
accounttype: req.body.data.accounttype,
paid: req.body.data.paid,
staticip: req.body.data.staticip,
staticipdate: req.body.data.staticipdate,
bill: req.body.data.bill,
balance: req.body.data.balance,
username: req.body.data.username,
pass: req.body.data.pass,
apip: req.body.data.apip
} )
data.save()
.then(r => console.log(r))
.catch(err => console.log(err))
})
журнал после (идентификаторы отличаются, так как он генерируется на бэкэнде не по форме)