Checkbox value in React and MongoDB - reactjs

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

Related

How do I clear/delete a grocery item in React?

How do I clear/delete a grocery item? I need to make a button that clears a grocery item after I click it. TIA
Here's the code this is for a HW assignment:
class App extends Component {
state = {
grocery: grocery,
item: '',
brand: '',
units: Number,
quantity: Number,
isPurchased: Boolean
}
handleChange = (e) => {
this.setState({ [e.target.id]: e.target.value })
}
handleSubmit = (e) => {
e.preventDefault()
const addGrocery = {
item: this.state.item,
brand: this.state.brand,
units: this.state.units,
quantity: this.state.quantity,
}
this.setState({
grocery: [addGrocery, ...this.state.grocery],
item: '',
brand: '',
units: Number,
quantity: Number,
})
const removeGrocery = {
item: this.state.item
}
}
Here is some codes bro. I fixed something that will give you error in future.
const initialValue = {
grocery: grocery,
item: '',
brand: '',
units: 1,
quantity: 2,
isPurchased: false
}
class App extends Component {
state = initialValue;
handleChange = (e) => {
// added a spread iterator
this.setState({...this.state, [e.target.id]: e.target.value })
}
reset = ()=> {this.setState(initialValue)} // set to initialValue is clearing current state to initial state

React SyncFusion Resource and grouping crud not binding the data in scheduler

Add event is working(saving to database) but added events are not displaying on scheduler but its working with mocked data . Please let me know if any one know how to bind the data back on scheduler
Please click here to find the attachment image
Please see the above image response getting form api but not binding to scheduler UI
export class GroupEditing extends SampleBase {
constructor() {
super();
this.data = extend([], dataSource.resourceConferenceData, null, true);
this.state = {
customers: [],
technicians: [],
services: [],
groups: [],
};
this.currentEvent;
}
componentDidMount() {
axios
.post('URL', {
userId: '39',
companyId: '38',
dateTime: '2021-03-08 21:43:25',
roleId: 1,
})
.then((res) => {
const data = res.data.content[0];
this.setState({
customers: data.customer,
groups: data.group,
services: data.pestServices,
technicians: data.employee,
});
});
}
addTechnician(args) {
const { technicians } = this.state;
let row = createElement('div', { className: 'custom-field-row' });
let formElement = args.element.querySelector('.e-schedule-form');
const resource = formElement.querySelector('.e-resources-row');
resource.insertBefore(row, resource.firstChild);
let container = createElement('div', {
className: 'custom-field-container',
});
let inputEle = createElement('input', {
className: 'e-field e-input',
attrs: { name: 'employeeId', placeholder: 'Technicians' },
});
container.appendChild(inputEle);
row.appendChild(container);
let dropDownList = new DropDownList({
dataSource: technicians,
fields: { text: 'name', value: 'employeeId' },
value: args.data.Customers,
floatLabelType: 'Always',
placeholder: 'Technicians',
});
dropDownList.appendTo(inputEle);
inputEle.setAttribute('name', 'employeeId');
}
addCustomers(args) {
const { customers } = this.state;
let row = createElement('div', { className: 'custom-field-row' });
let formElement = args.element.querySelector('.e-schedule-form');
formElement.firstChild.insertBefore(row, formElement.firstChild.firstChild);
let container = createElement('div', {
className: 'custom-field-container',
});
let inputEle = createElement('input', {
className: 'e-field e-input',
attrs: { name: 'customerId', placeholder: 'Customers' },
});
container.appendChild(inputEle);
row.appendChild(container);
let dropDownList = new DropDownList({
dataSource: customers,
fields: { text: 'customerName', value: 'customerId' },
value: args.data.Customers,
floatLabelType: 'Always',
placeholder: 'Customers',
});
dropDownList.appendTo(inputEle);
inputEle.setAttribute('name', 'customerId');
}
onPopupOpen(args) {
if (args.type === 'Editor') {
if (!args.element.querySelector('.custom-field-row')) {
debugger;
this.addCustomers(args);
this.addTechnician(args);
}
}
}
render() {
const { services, groups, loading } = this.state;
return (
<div className='schedule-control-section'>
<div className='col-lg-12 control-section'>
<div className='control-wrapper'>
<ScheduleComponent
rowAutoHeight={true}
// popupOpen={this.onPopupOpen.bind(this)}
cssClass='group-editing'
width='100%'
height='650px'
selectedDate={new Date()}
// currentView='Day'
eventSettings={{
dataQuery: new Query().from('EventDatas'),
dataSource: new DataManager({
url: 'http://localhost:25255/api/Batch',
crossDomain: true,
adaptor: new UrlAdaptor(),
}),
}}
group={{
allowGroupEdit: false,
byGroupID: false,
resources: ['groupId', 'serviceId'],
}}
>
<ResourcesDirective>
<ResourceDirective
field='serviceId'
title='Services'
name='serviceId'
allowMultiple={true}
dataSource={services}
textField='serviceName'
idField='serviceId'
></ResourceDirective>
<ResourceDirective
field='groupId'
title='Group'
name='groupId'
allowMultiple={false}
dataSource={groups}
textField='name'
idField='groupId'
></ResourceDirective>
</ResourcesDirective>
<Inject
services={[
Day,
WorkWeek,
Month,
TimelineViews,
Resize,
DragAndDrop,
]}
/>
</ScheduleComponent>
</div>
</div>
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
You have missed to add CrudUrl in the dataManager settings. So that the CRUD actions are not working. So we would suggest you to refer and follow the below sample.
Service: https://www.syncfusion.com/downloads/support/directtrac/general/ze/ScheduleCRUD-1748824462-1972500097
Sample: https://stackblitz.com/edit/react-schedule-url-adaptor-two-level-resource?file=index.js
this.dataManger = new DataManager({
url: 'http://localhost:54738/Home/LoadData',
crudUrl: 'http://localhost:54738/Home/UpdateData',
crossDomain: true,
adaptor: new UrlAdaptor
});
UG: https://ej2.syncfusion.com/react/documentation/schedule/data-binding/#scheduler-crud-actions
We could reproduce the reported issue “issue in deleting the entire recurrence events” and confirm this as defect at our end. You can keep track of the bug through the following feedback. The fix for this issue is expected to be rolled out in in our JS2 weekly release scheduled on April 27, 2021. We would appreciate your patience until then.
Feedback: https://www.syncfusion.com/feedback/24505/issue-in-deleting-the-entire-recurrence-events-with-resources-only-when-it-is

Why state show undefined?

I am working on form validation and I make two arrays one for check value and the second was check validation but when the page refresh and render then in my console log show undefined in my name state. whether I give him to a true value in the state. Does anyone have any idea why is this?
var validation = [{
name: true,
company: true,
email: true,
phone: true,
message: true,
}]
const [isValidate, setisValidate] = React.useState({ ...validation })
const [error, seterror] = React.useState({
name: '',
company: '',
email: '',
phone: '',
message: '',
});
const isValidFun = (param) => {
let isTrue = true;
if((param === "name" || param === "all") && (!error.name || error.name.length < 5)) {
isValidate.name = false;
isTrue = false;
} else {
isValidate.name = true;
}
setisValidate({ ...isValidate })
return isTrue;
}
const handleChange = (e) => {
error[e.target.name] = e.target.value;
seterror({ ...error });
isValidFun(e.target.name);
};
console.log(isValidate.name)
const sentMail = () => {
let isValid = isValidFun("all");
if (isValid) {
alert('Form submitted')
}
};
return (
<Input
type="text"
name="name"
placeholder="Name"
value={error.name}
onChange={handleChange}
/>
{!isValidate.name && <p className="error">This field is required</p>}
);
};
Your validation object is an array. When you initialise the state, you use the spread operator on the array inside the object, so you end up with an object with key 0 and value of the object.
var validation = [{
name: true,
company: true,
email: true,
phone: true,
message: true,
}]
console.log({...validation}]
Instead, change the validation to an object and assign it to state.
var validation = {
name: true,
company: true,
email: true,
phone: true,
message: true,
}
const [isValidate, setisValidate] = React.useState(validation);
Should be the spreader. validation variable should be like this
var validation = {
name: true,
company: true,
email: true,
phone: true,
message: true,
}

Cannot read property 'files' of undefined for sending multiple images

Code
class Add_Give_Item_Form extends Component {
constructor(props) {
super(props);
this.state = {
// #インプット情報用
info: {
name: '',
owner: '',
keyword1: '',
keyword2: '',
keyword3: '',
bland: '',
state: '未使用、新品',
category: '',
images: [],
detail: '',
},
// Validation用
//  urlは必須項目ではないのでValidationには含めない
message: {
name: '',
keyword1: '',
keyword2: '',
keyword3: '',
state: '',
category: '',
detail: '',
},
allCategory: null,
allBland: null,
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleImageSelect = this.handleImageSelect(this);
}
////
...
////
handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
const { info, message } = this.state;
this.setState({
info: { ...info, [name]: value },
});
this.setState({
message: { ...message, [name]: this.validator(name, value) },
});
};
handleImageSelect = (e) => {
this.setState({
info: { ...this.state.info, images: [...this.state.info.images, e.target.files] },
});
};
render() {
const { info, message, allCategory, allBland } = this.state;
// setStateが完了するまではnullにする。
if (this.state.allCategory === null || this.state.allBland === null) {
return <CircularProgress />;
} else {
return (
<div>
///////
.....
///////
<label>Images</label>
<input type="file" multiple onChange={this.handleImageSelect} />
What I want to do
I would like to catch each file sent by a user and put into state as this.state.info.images which is an array.
I saw some questions on stackoverflow and then I found some solutions. When I wrote the same code as what I saw, I got an error like below.
cannot read property files of undefined
I should write the same code but I got the error for some reasons.
I may take another way to realize what I want to do, but I want to write readable codes and figure out why it is happening.
I would like you to teach me why this happens and solutions.
Thank you very much.
I just notice I didn't put bind with this.handleImageSelect = this.handleImageSelect(this).
Now it works well.
Thank you very much.

Form inputs should clear only with correct submit

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 ?

Resources