Form inputs should clear only with correct submit - reactjs

My form component looks like :
constructor(props) {
super(props);
this.state = {
startDate: '',
endDate: '',
description: '',
profileId: this.props.profileId
}
this.onStartDateChange = this.onStartDateChange.bind(this);
this.onEndDateChange = this.onEndDateChange.bind(this);
this.onDescriptionChange = this.onDescriptionChange.bind(this);
this.clickHandle = this.clickHandle.bind(this);
}
onStartDateChange(event) {
const startDate = event.target.value
this.setState({
startDate: startDate
})
}
onEndDateChange(event) {
const endDate = event.target.value
this.setState({
endDate: endDate
})
}
onDescriptionChange(event) {
const description = event.target.value
this.setState({
description: description
})
}
clickHandle = () => {
const inputValues = {
startDate: this.state.startDate,
endDate: this.state.endDate,
description: this.state.description
}
this.props.onAddClick(this.state.profileId, inputValues);
}
render() {
return (
<Form>
<div className={"m-3 form-row"}>
<Field type={"date"} className={"form-control col-md-2 mr-2"}
onChange={evt => this.onStartDateChange(evt)}
value={this.state.startDate}
name={"add-start-date"}/>
<Field type={"date"} className={"form-control col-md-2 mr-2"}
onChange={evt => this.onEndDateChange(evt)}
value={this.state.endDate}
name={"add-end-date"}/>
<Field className={"form-control col-md-2 mr-2"}
type={"textarea"}
onChange={evt => this.onDescriptionChange(evt)}
value={this.state.description}
name={"add-description"}/>
<button className="btn btn-info round-btn" href="#"
onClick={this.clickHandle}
type={"button"}><FontAwesomeIcon icon={faPlus}/></button>
</div>
</Form>
}
My action looks like:
export const onAddClick = (profileId, educationData = {
startDate: '',
endDate: '',
description: ''
}) => {
return (dispatch) => {
const education = {
startDate: educationData.startDate,
endDate: educationData.endDate,
description: educationData.description
};
return axios.post(`${ENTRY_API_URL}`)
.then(response => {
dispatch(_addEducation(profileId, response.data))
})
.catch((error) => {
if (error) {
dispatch(_requestFailure(profileId, error.response.data))
}
})
};
};
My store looks like
workExperience: [
{
id: '5d6e3368993694389c903c50',
startDate: '2019-09-04',
endDate: '2019-09-12',
description: 'description'
},
How can I clear input only when request to API is correct and when its wrong leave it. Can I make it without redux-forms ? I tried with some flag in store but it change slowly after I clicked the button. Should I try make some state in redux for this form ?

Related

React Form Validation Issue

i don't know what is wrong with my code , i check the value with console.log and it gets the value normally but when i submit the form it gets back to undefined , and when i try to check the form with if statement if just send the mail with empty values and sometimes it send undefined
const [mails, setMails] = useState({
userFullName: '',
userEmail: '',
userSubject: '',
userMessage: '',
mailFail : false,
});
const [mailStatues, setMailStatues] = useState(false);
const [mailLoader, setMailloader] = useState(false);
const { userFullName, userEmail, userSubject, userMessage, mailFail } = mails;
const handleChange = e => {
setMails({ ...mails, [e.target.name] : e.target.value})
}
function setFail() {
setMails({ mailFail: true })
setTimeout(() => {
setMails({ mailFail: false })
}, 3000);
}
const handleEmail = async (e) => {
e.preventDefault();
console.log(userFullName , userEmail, userSubject, userMessage)
if ( userFullName ) {
setFail()
}
else {
setMailloader(true);
await axios.post('http://localhost:8000/api/form', {
...mails
},
setMails({
userFullName: '',
userEmail: '',
userSubject: '',
userMessage: '',
})
,
setMailloader(false)
,
setMailStatues(true)
)
}
}
here is the form
<form onSubmit={handleEmail}>
<Input id='inputName' type="text" name="userFullName" label="Name" value={userFullName} change={handleChange} />
<Input id='inputEmail' type="email" name="userEmail" label="Email" value={userEmail} change={handleChange}/>
<Input id='inputSubject' type="text" name="userSubject" label="Subject" value={userSubject} change={handleChange}/>
<TextArea id='inputMessage' type="text" name="userMessage" label="Message" value={userMessage} change={handleChange}/>
<BtnAni string="Submit" loading={mailLoader}/>
</form>
Change these lines
setMails({ mailFail: true })
setTimeout(() => {
setMails({ mailFail: false })
}, 3000);
to
setMails(prev => ({ ...prev, mailFail: true }))
setTimeout(() => {
setMails(prev => ({ ...prev, mailFail: false }))
}, 3000);

Condtional Renderin React using If-else not working

i'm new at React, i want to ask about contidional recndering, i'm making project about sending message, and i use validation to check all field is not empty, when one field is empty it should show error message that message not send. I using if-else to render the error message, but it doesn't work.
Here i add my code
....
export default class Message extends React.Component {
constructor(props){
super(props);
this.state = {
isLoggedIn: SystemStore.isLoggedIn(),
profile: ProfileStore.getProfile(),
fullName: SystemStore.systemUser().fullName,
site: '',
email: '',
phone: '',
subject: '',
description: '',
type: '',
errorMessage: '',
errorDialog: '',
isSubmited: false,
successMessage: '',
submitting: false
};
this.clearForm = this.clearForm.bind(this);
this.handleProfileChange = this.handleProfileChange.bind(this);
this.handleSubjectChange = this.handleSubjectChange.bind(this);
this.handleMessageChange = this.handleMessageChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleSubmitComplete = this.handleSubmitComplete.bind(this);
this.handleSubmitError = this.handleSubmitError.bind(this);
}
componentDidMount(){
ProfileStore.addProfileChangeListener(this.handleProfileChange);
if(!this.state.profile){
ProfileActions.reload()
}
MessageStore.addSubmitMessageChangeListener(this.handleSubmitComplete);
MessageStore.addSubmitMessageFailChangeListener(this.handleSubmitError);
}
componentWillUnmount(){
ProfileStore.removeProfileChangeListener(this.handleProfileChange);
MessageStore.removeSubmitMessageChangeListener(this.handleSubmitComplete);
MessageStore.removeSubmitMessageFailChangeListener(this.handleSubmitError);
}
render(){
return(
<Layout>
<div className='hs-dashboard row'>
<div className='col-md-12'>
<div className='col-xs-12 col-sm-6 col-md-5'>
<div className='col-xs-12 hs-message-form'>
<div className='row hs-message-form-head'>
<div className='hs-message-form-logo-container'>
<img className='col hs-message-form-logo' src='../../images/gii-logo-black.png'/>
<text className='hs-message-form-logo-label'>{T.translate('gii')}</text>
</div>
<div className='hs-message-form-label'>
{ T.translate('message.title') }
</div>
<div className='hs-message-form-label-1'>
{ T.translate('message.subtitle') }
</div>
</div>
<div className='row hs-message-form-body'>
<form className='hs-message-form-body-content'>
<label>
{ T.translate('message.type') }
</label>
<select
id="subject"
value={ this.state.subject }
onChange={ this.handleSubjectChange }
className="form-control"
required="true"
>
<option value="">{ T.translate('placeholder.selectSubject') }</option>
<option value="PRAYER">{ T.translate('message.pray') }</option>
<option value="ADDRESS">{ T.translate('message.address') }</option>
<option value="VISIT">{ T.translate('message.visit') }</option>
</select>
<label>
{T.translate('message.message')}
</label>
<textarea
type="text"
id="description"
className="form-control"
width=''
placeholder={ T.translate('placeholder.message') }
onChange={ this.handleMessageChange }
value={ this.state.description }
required
/>
{ this.state.errorDialog &&
<div className='hs-message-empty'>
{ this.state.errorDialog }
</div>
}
{ this.state.isSubmited === true ?
<div className='hs-message-success'>
{ this.state.successMessage }
</div> :
<div className='hs-message-error'>
{ this.state.errorMessage }
</div>
}
<LaddaButton
loading={ this.state.submitting }
onClick={ this.handleSubmit }
data-spinner-size={ 30 }
data-style={ SLIDE_RIGHT }
>
{ T.translate('action.send') }
</LaddaButton>
</form>
</div>
</div>
</div>
</div>
</div>
</Layout>
)
}
clearForm(){
this.setState({ subject: '', description: '' });
}
handleProfileChange(){
this.setState({
site: ProfileStore.getProfile().primarySite.name,
email: ProfileStore.getProfile().emailAddresses[0].email,
phone: ProfileStore.getProfile().contactNumbers[0].countryCode + ProfileStore.getProfile().contactNumbers[0].number
});
}
handleSubjectChange(evt){
this.setState({ subject: evt.target.value }, () => {
if(this.state.subject === 'PRAYER') {
this.setState({ type: 'REQUEST' });
} else if(this.state.subject === 'ADDRESS') {
this.setState({ type: 'INFORMATION' });
} else if(this.state.subject === 'VISIT'){
this.setState({ type: 'REQUEST' });
}
});
}
handleMessageChange(evt){
this.setState({ description: evt.target.value });
}
handleSubmit(evt) {
evt.preventDefault();
var errorDialog;
if(this.state.subject === ''){
errorDialog = 'Error:' + T.translate('msg.subjectRequired');
} else if(this.state.description === ''){
errorDialog = 'Error:' + T.translate('msg.mailDescriptionRequired');
}
this.setState({errorDialog: errorDialog});
this.handleProfileChange();
this.handleSubjectChange(evt);
this.handleMessageChange(evt);
var messageInfo = {
fullName: this.state.fullName,
site: this.state.site,
email: this.state.email,
phone: this.state.phone,
subject: this.state.subject,
description: this.state.description,
type: this.state.type
};
this.setState({ submitting: true }, () => {
MessageActions.sendMessage(messageInfo);
});
console.log(this.state.isSubmited);
}
handleSubmitComplete(){
this.setState({
submitting: false,
isSubmited: true,
errorMessage: null,
successMessage: T.translate('msg.mailSent')
});
this.clearForm();
}
handleSubmitError(){
this.setState({
submitting: false,
isSubmited: false,
errorMessage: T.translate('msg.mailSentFailed'),
successMessage: null
});
}
}
//updated code
This is my store.js
....
var MessageStore = assign({}, EventEmitter.prototype, {
emitSubmitMessageChange: function(){
this.emit(SUBMIT_MESSAGE);
},
addSubmitMessageChangeListener: function(callback){
this.on(SUBMIT_MESSAGE, callback);
},
removeSubmitMessageChangeListener: function(callback){
this.removeListener(SUBMIT_MESSAGE, callback);
},
emitSubmitMessageFailChange: function() {
this.emit(SUBMIT_MESSAGE_FAILED);
},
addSubmitMessageFailChangeListener: function(callback) {
this.on(SUBMIT_MESSAGE_FAILED, callback);
},
removeSubmitMessageFailChangeListener: function(callback) {
this.removeListener(SUBMIT_MESSAGE_FAILED, callback);
}
});
Dispatcher.register(function(action) {
switch(action.actionType){
case MessageConstants.PERFORM_SEND_MESSAGE:
MessageStore.emitSubmitMessageChange();
break;
case MessageConstants.PERFORM_SEND_MESSAGE_FAIL:
MessageStore.emitSubmitMessageFailChange();
break;
default:
//noop
}
})
export default MessageStore;
And this is my action.js
.....
function _sendMessage(messageInfo, callback) {
jQuery.ajax({
method: 'POST',
url: api('supportTickets'),
contentType: 'application/json',
data: JSON.stringify(messageInfo)
})
.done(function(messageInfo) {
callback(null, messageInfo);
})
.fail(function(err){
console.error('Failed to send message : ' + JSON.stringify(err));
callback(err, null);
});
}
var MessageActions = {
sendMessage: function(messageInfo) {
_sendMessage(messageInfo, function(err, messageInfo) {
if(err) {
Dispatcher.dispatch({
actionType: MessageConstants.PERFOM_SEND_MESSAGE_FAIL
});
}
Dispatcher.dispatch({
actionType: MessageConstants.PERFORM_SEND_MESSAGE,
messageInfo
});
});
}
};
module.exports = MessageActions;
Your form should be responsible for handling errors. You should know your errors at the time of submission of the form.
handleSubmit(evt) {
evt.preventDefault();
var errorDialog;
if(this.state.subject === ''){
errorDialog = 'Error:' + T.translate('msg.subjectRequired');
} else if(this.state.description === ''){
errorDialog = 'Error:' + T.translate('msg.mailDescriptionRequired');
}
if (errorDialog) {
this.setState({
// set your error here
})
return;
}
this.handleProfileChange();
this.handleSubjectChange(evt);
this.handleMessageChange(evt);
var messageInfo = {
fullName: this.state.fullName,
site: this.state.site,
email: this.state.email,
phone: this.state.phone,
subject: this.state.subject,
description: this.state.description,
type: this.state.type
};
this.setState({ submitting: true }, () => {
MessageActions.sendMessage(messageInfo);
});
console.log(this.state.isSubmited);
}
Your component seems to be a little complex. Think about breaking your component into smaller components. Using functional components I would do this task in a way something like that.
function validateForm() {
// validate form logic here. If it's ok, returns true, otherwise, returns false
}
function Message({ form }) {
if (!validateForm(form)) {
return (
<div>Please, fill the empty fields!!</div>
)
}
return (
<div>All good. Submit the form!!</div>
)
}

Checkbox value in React and MongoDB

What I am seeking to accomplish is to have an optional checkbox in a form that returns false when unchecked and true when checked (in the DB).
However, whenever I view my submission in the console, things appear to be find - just not showing up in Mongo. I have attempted numerous things after searching all day both frontend and backend schema. Any help or insight would be much appreciated.
export default class CreateworkOrder extends Component {
constructor(props) {
super(props);
this.onChangeEmployee = this.onChangeEmployee.bind(this);
this.onChangeDescription = this.onChangeDescription.bind(this);
this.onChangeDuration = this.onChangeDuration.bind(this);
this.onChangeDate = this.onChangeDate.bind(this);
this.handleCheckClick = this.handleCheckClick.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
employee: '',
description: '',
duration: 0,
date: new Date(),
employees: [],
isComplete: false
}
}
componentDidMount() {
axios.get('http://localhost:5000/employees/')
.then(response => {
if (response.data.length > 0) {
this.setState({
employees: response.data.map(emp => emp.employee),
employee: response.data[0].employee
})
}
})
.catch((error) => {
console.log(error);
})
}
handleCheckClick = () => {
const complete = !this.state.isComplete;
console.log(complete);
this.setState({ complete: !this.state.isComplete});
}
Then submit below:
onSubmit(e) {
e.preventDefault();
const workOrder = {
employee: this.state.employee,
description: this.state.description,
duration: this.state.duration,
date: this.state.date,
isComplete: this.state.isComplete
}
console.log(workOrder);
axios.post('http://localhost:5000/workOrders/add', workOrder)
.then(res => console.log(res.data)).catch(console.error);
//window.location = '/home';
}
portion of the form to optionally select
<div className="form-group">
<label>Only check box if job has been completed </label>
<input name="isComplete" type="checkbox"
defaultChecked={this.state.isComplete}
onChange={this.handleCheckClick}
className="filled-in" id="filled-in-box"/>
</div>
<div className="form-group">
<input type="submit" value="Create WO" className="btn btn-primary" onSubmit={this.onSubmit}/>
</div>
</form>
DB Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const workorderSchema = new Schema({
employee: { type: String, required: true },
description: { type: String, required: true },
duration: { type: Number, required: true },
date: { type: Date, required: true },
isComplete: { type: Boolean, required: false },
},
{
timestamps: true,
});
const WorkOrder = mongoose.model('WorkOrder', workorderSchema);
module.exports = WorkOrder;
but console does show true
You are using the state variable isComplete but setting the state in complete.
this.state = {
employee: '',
description: '',
duration: 0,
date: new Date(),
employees: [],
isComplete: false
}
In handleCheckClick you are doing:
handleCheckClick = () => {
const complete = !this.state.isComplete;
console.log(complete);
this.setState({ complete: !this.state.isComplete}); }
And you are submitting workOrder which is using isComplete, which you didn't change
const workOrder = { employee: this.state.employee, description:
this.state.description, duration: this.state.duration, date:
this.state.date, isComplete: this.state.isComplete }
This should be the reason. So change the handleCheckClick like this:
handleCheckClick = () => {
let complete = !this.state.isComplete;
console.log(complete);
this.setState({ isComplete: complete});
}
Also, I noticed that you are using const keyword and then trying to change its value. const means the value shouldn't change. Use either let or var in future if you want a variable to be mutable

Save data to firebase

enter image description here
I am building this meeting booking app where the available meetings to books shows as buttons and after klicking the meeting you want so select. I want to make it possible to save that information in the button with a name and email that is written in the form.
I am having it hard to set the code so that my button selection is saved and saved to firebase along with the name and email after submit button is pressed. Right know I get the error that 'set' in handleSubmit is not set.
import React, { Component } from "react";
import "./App.css";
import firebase from "firebase";
const uuid = require("uuid");
class App extends Component {
constructor(props) {
super(props);
this.state = {
uid: uuid.v1(),
meeting: "",
name: "",
email: ""
};
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
// console.log(firebase);
var database = firebase.database();
var ref = database.ref("meeting");
var data = {
id: "",
user: ""
};
ref.push(data);
// this.state = {
// items: [],
// isLoaded: true,
// }
// this.state = {
// name: '',
// email: '',
// };
}
handleClick = e => {
console.log(e.target.innerHTML);
alert("Du har valt ett möte");
};
componentDidMount() {
fetch("http://www.mocky.io/v2/5c9cdca03300004d003f2151")
.then(res => res.json())
.then(json => {
let meetings = [];
json.forEach(meeting => {
if (
new Date(meeting.startDate).getDay() !==
new Date(meeting.endDate).getDay()
) {
let day1 = {
activity: meeting.activity,
location: meeting.location,
startDate: meeting.startDate
};
let day2 = {
activity: meeting.activity,
location: meeting.location,
endDate: meeting.endDate
};
meetings.push(day1, day2);
} else {
meetings.push(meeting);
}
});
console.log(meetings);
this.setState({
isLoaded: true,
items: meetings
});
});
firebase
.database()
.ref(`Newdata/${this.state.uid}`)
.on("value", snap => console.log("from db", snap.val()));
}
handleChange(e) {
this.setState({
name: e.target.name
});
}
handleSubmit(e) {
alert("Er bokning är bekräftad: " + this.state.value);
console.log("Du har bekräftat er bokning");
e.preventDefault();
firebase.database().ref(`Newdata/${this.state.uid}`);
set({
meeting: this.state.meeting,
name: this.state.name,
email: this.state.email
}).catch(error => console.log(error));
}
inputData(e) {
const meeting = this.refs.meeting1.value;
const name = this.refs.name1.value;
const email = this.refs.email1.value;
this.setState({ meeting, name, email });
}
render() {
var { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<>
<div className="App">
<div className="AppHeader">
<h1>Boka ditt möte nedan</h1>
</div>
<ul>
{items.map((item, i) => (
<li key={i}>
<button
onClick={e => this.handleClick(e)}
onChange={this.inputData}
className="select"
>
{item.activity}
<br />
Starttid: {item.startDate}
<br />
Sluttid: {item.endDate}
<br />
Plats: {item.location}
<br />
</button>
</li>
))}
</ul>
</div>
<div className="selectedMeeting">
Fyll i dina uppgifter och bekräfta
</div>
<form onSubmit={this.handleSubmit} className="bookingSection">
<label>
Name:
<input
type="text"
name={this.state.name}
onChange={this.inputData}
onChange={this.handleChange}
ref="name1"
/>
</label>
<label>
E-mail:
<input
type="text"
email={this.state.email}
onChange={this.inputData}
onChange={this.handleChange}
ref="email1"
/>
</label>
<input className="confirm" type="submit" value="Bekräfta" />
</form>
<div className="viewSelect" />
</>
);
}
}
}
export default App;
TL;DR;
You have a typo in your code, it should be:
firebase.database().ref('Newdata/${this.state.uid}').set({
meeting: this.state.meeting,
name: this.state.name,
email: this.state.email
}).catch(error => console.log(error));
Explanation:
Since you add the ;, you end the first expression and start a new one that is:
set({
meeting: this.state.meeting,
name: this.state.name,
email: this.state.email
}).catch(error => console.log(error));
Since there is no function defined, Javascript gives this error. But what you want do do is call the method set of the object firebase.database().ref('Newdata/${this.state.uid}'), therefore you should do:
firebase.database().ref('Newdata/${this.state.uid}').set({ /* ... */ })

Cant text in input field

I am building a meeting booking webb application. I want to save the content in the buttons to firebase and also the input text in the form to firebase.
I cant type text in the input field for then I get error: TypeError: Cannot read property 'refs' of undefined
enter image description here
enter image description here
import React, { Component } from "react";
import "./App.css";
import firebase from "firebase";
const uuid = require("uuid");
class App extends Component {
constructor(props) {
super(props);
this.state = {
uid: uuid.v1(),
meeting: "",
name: "",
email: ""
};
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
console.log(firebase);
var database = firebase.database();
var ref = database.ref("meeting");
var data = {
id: "",
user: ""
};
ref.push(data);
// this.state = {
// items: [],
// isLoaded: true,
// }
// this.state = {
// name: '',
// email: '',
// };
}
handleClick = e => {
console.log(e.target.innerHTML);
alert("Du har valt ett möte");
};
componentDidMount() {
fetch("http://www.mocky.io/v2/5c9cdca03300004d003f2151")
.then(res => res.json())
.then(json => {
let meetings = [];
json.forEach(meeting => {
if (
new Date(meeting.startDate).getDay() !==
new Date(meeting.endDate).getDay()
) {
let day1 = {
activity: meeting.activity,
location: meeting.location,
startDate: meeting.startDate
};
let day2 = {
activity: meeting.activity,
location: meeting.location,
endDate: meeting.endDate
};
meetings.push(day1, day2);
} else {
meetings.push(meeting);
}
});
console.log(meetings);
this.setState({
isLoaded: true,
items: meetings
});
});
firebase
.database()
.ref(`Newdata/${this.state.uid}`)
.on("value", snap => console.log("from db", snap.val()));
}
handleChange(e) {
this.setState({
name: e.target.name
});
}
handleSubmit(e) {
alert("Er bokning är bekräftad: " + this.state.value);
console.log("Du har bekräftat er bokning");
e.preventDefault();
firebase
.database()
.ref(`Newdata/${this.state.uid}`)
.set({
meeting: this.state.meeting,
name: this.state.name,
email: this.state.email
})
.catch(error => console.log(error));
}
inputData(e) {
const meeting = this.refs.meeting1.value;
const name = this.refs.name1.value;
const email = this.refs.email1.value;
this.setState({ meeting, name, email });
}
render() {
var { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<>
<div className="App">
<div className="AppHeader">
<h1>Boka ditt möte nedan</h1>
</div>
<ul>
{items.map((item, i) => (
<li key={i}>
<button
onClick={e => this.handleClick(e)}
onChange={this.inputData}
ref="meeting1"
className="select"
>
{item.activity}
<br />
Starttid: {item.startDate}
<br />
Sluttid: {item.endDate}
<br />
Plats: {item.location}
<br />
</button>
</li>
))}
</ul>
</div>
<div className="selectedMeeting">
Fyll i dina uppgifter och bekräfta
</div>
<form onSubmit={this.handleSubmit} className="bookingSection">
<label>
Name:
<input
type="text"
name={this.state.name}
onChange={this.inputData}
ref="name1"
/>
</label>
<label>
E-mail:
<input
type="text"
email={this.state.email}
onChange={this.inputData}
ref="email1"
/>
</label>
<input className="confirm" type="submit" value="Bekräfta" />
</form>
<div className="viewSelect" />
</>
);
}
}
}
export default App;
Make sure your "def" variable is defined before attempting to push it, like so:
var data = { id: "",user: "" };
var ref = [];
ref.push(...);
Either add to your constructor:
this.inputData = this.inputData.bind(this);
or use arrow syntax to preserve the lexical this:
inputData = (e) => {

Resources