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

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

Related

React-typescript, looping over the state in reducer function

How can I loop over the whole useReducer state and set the its "isWrong" property to true if there is no value after form submission. What is the best approach to solve that. Because the problem is that I could loop over the state and make the separate variable but the problem is I need the "isWrong" property set inside state because it makes fields color red when it is wrong.
state = const initialStateReducer: inputsFormState = {
title: {
val: "",
isValid: false,
isClicked: false,
isWrong: false,
},
description: {
val: "",
isValid: false,
isClicked: false,
isWrong: false,
},}
reducer:
const inputReducer = (
state: inputsFormState,
action: inputsFormAction
): inputsFormState => {
let isValid = false;
let isClicked = true;
let isWrong = false;
const { content } = action;
const validateInput = (content: string) => {
isClicked = true;
isValid = content.length > 0;
isWrong = isClicked && !isValid;
};
if (
action.type === ActionKind.stringVal &&
action.field &&
typeof content === "string"
) {
validateInput(content);
return {
...state,
[action.field]: {
val: content,
isValid: isValid,
isClicked: isClicked,
isWrong: isWrong,
},
};
}
Form submission
const onSubmitHandler = (e: React.FormEvent): void => {
e.preventDefault();
if (formIsValid && user?.displayName) {
const recipe: Recipe = {
username: user.displayName,
title: inputsValues.description.val,
type: type,
description: inputsValues.title.val,
id: Math.random(),
time: time,
ingredients: ingredients,
stars: Math.floor(Math.random() * 6) + 1,
steps: steps,
comments: [],
};
dispatch(recipeAction.addRecipe(recipe));
dispatch(sendData(recipe));
navigate("/");
}
};
You can change your validateInput arrow function to augment the state as follows:
const validateInput = (state: inputsFormState, content: string): inputsFormState => {
Object.keys(state).forEach((stateKey) => {
validatedState[stateKey] = {
isClicked: true,
isValid: content.length > 0,
isWrong: isClicked && !isValid,
val: state[stateKey].val,
};
});
};
Then you can use it as follows:
validateInput(state, content);
return { ...state };
Also, if you want want content to be set in all of the val properties, you can change val: state[stateKey].val to val: content.

how I place this.state inside ""?

here, I want access to 'this.state.select1' & 'this.state.select2' as factor's object attributes, in the handleClick event handler. how I place these in "", in the way that not become string? because output give me NaN.
This is the desired part of my code:
const factor = {
kilometer: 1,
meter: 1000,
centimeter: 100000,
millimeter: 1000000
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text: '',
select1: '',
select2: '',
result: 0
}
}
handleChange1 = (e) => {
this.setState({
text: e.target.value
}
);
}
handleChange2 = (e) => {
this.setState({
select1: e.target.value
}
);
}
handleChange3 = (e) => {
this.setState({
select2: e.target.value
}
);
}
handleClick = () => {
this.setState({
result: (parseInt(this.state.text) * factor['this.state.select1']) /
factor['this.state.select2']
});
}
output:
enter image description here

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.

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

Unable to update form field in react via prevState

I have a state variable as:
constructor(props) {
super(props)
this.state = {
fields: {
applicantName: '',
applicantType: '',
applicantAddress: '',
applicantContact: '',
buildingName: '',
buildingAddress: '',
area:'',
}
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
and I have a function :
handleChange(event) {
this.setState((prevState) => {
fields: {
...prevState.fields, //Unexpected token ..
{
event.target.name: event.target.value,
},
}
});
}
How I am not able to see any type of syntax here...but my module build fails and it says syntax error near '...'
you need return Object
handleChange(event) {
// note here => ({
this.setState((prevSate) => ({
fields: {
...prevState.fields,
//and there ..
[event.target.name]: event.target.value
})
});
}
UPDATE
Based on Abdullah suggestion, its better when you use ...prevState for wohle state:
handleChange(event) {
// note here => ({
this.setState((prevSate) => ({
// note change here
...prevState,
fields: {
...prevState.fields,
//and there ..
[event.target.name]: event.target.value
})
});
}
UPDATE 2
based on PraveenRaoChavan comment:
typo fix:
need use event not e
handleChange(event) {
this.setState(prevState => ({
fields: {
...prevState.fields,
{
event.target.name: e.target.value,
},
}
}));
}
You have a typo in there
change
this.setState((prevSate) => { }
to
this.setState((prevState) => { }

Resources