How can i modifier a state only when has the same ID - javascript

editItem = (id) => {
this.setState(
{
lanche: [
{
id: id,
editItem: true
}]
}
)
}
In this way, setState runs on all items in the array, I need to edit only the item that has the same ID

You need to find the item in the array with the given id, and modify that one only. setState method changes the whole object with the given key.
try this:
editItem = (id) => {
this.setState(
{
lanche: this.state.lanche.map(item => {
if(item.id === id) {
item.editItem = true
}
return item;
})
}
)
}

You can use map like this:
editItem = (id) => {
// update the relevant item
const updatedItems = this.state.lanche.map(item => {
if (item.id === id) {
item.editItem = true;
}
return item;
} );
this.setState(
{
lanche: updatedItems
}
)
}

If I understand your question;
You could search for the index like so;
const index = this.state.lanche.findIndex((e) => e.id === id);
and then alter the object
const newLanche = this.state.lanche;
newLanche[index].editItem = true;
And then update the store;
this.setState({ lanche: newLanche });

Related

How to delete multiple url params

There is a problem with deleting several string parameters. Only the last parameter is being deleted now.
upd: I did not specify that I wanted to achieve the ability to remove specific parameter values
this code does not work correctly:
const updateFiltersSearchParams = (paramKey, newValue) => {
const isParamExist = searchParams.getAll(paramKey).includes(newValue);
if (!isParamExist) {
searchParams.append(paramKey, newValue);
setSearchParams(searchParams);
} else {
const updatedSearchParams = new URLSearchParams(
[...searchParams].filter(
([key, value]) => key !== paramKey || value !== newValue
)
);
setSearchParams(updatedSearchParams);
}
};
const handleDeleteParams = () => {
[...checkboxParams].forEach((param) => {
updateFiltersSearchParams("selected", param);
});
};
Sandbox
change your handleDeleteParams function with this
const handleDeleteParams = () => {
setSearchParams([]);
};
If you want to delete *only the selected (or any specific queryString key) queryString parameters you can use the delete method of the URLSearchParams object, then enqueue the params URL update.
const handleDeleteParams = (key) => {
searchParams.delete(key);
setSearchParams(searchParams);
};
...
<button type="button" onClick={() => handleDeleteParams("selected")}>
Clear all "selected" params
</button>
Solved the problem by modifying the function like this
const toggleSearchParams = (params) => {
const newSearchParams = [...searchParams];
for (const prevParam of params) {
const index = newSearchParams.findIndex(
(newParam) =>
prevParam[0] === newParam[0] && prevParam[1] === newParam[1]
);
if (index === -1) {
newSearchParams.push(prevParam);
} else {
newSearchParams.splice(index, 1);
}
}
setSearchParams(new URLSearchParams(newSearchParams));
};
const handleChangeCheckBoxValue = (e) => {
toggleSearchParams([["selected", e.target.value]]);
};
const handleDeleteParams = () => {
toggleSearchParams(checkboxParams.map((param) => ["selected", param]));
};

Rewrite a function to find an object by a matching id inside an array, update a value and set a react state

The function below receiving a rating value inside an object. While ID or Question stay intact, the rating value can be updated. As a result a React state value should be updated.
Is there a way to make this function look prettier/concise while just using a vanilla javascript.
ratingCompleted = ({ rating, question, id }) => {
let array = this.state.ratingResponses;
const index = array.findIndex(elem => elem.id == id);
if (index === -1) {
array.push({ rating, question, id });
this.setState({ ratingResponses: array });
} else {
array.map(object => {
if (object.id === id) {
object.rating = rating;
return object;
} else {
return object;
}
});
this.setState({ ratingResponses: array });
}
};
Make sure you spread to stop mutations
This could be a little cleaner but i thought I would show each step.
const array = [...this.state.ratingResponses]; // spread this so as to make a copy
let updatedArray;
const hasRatingAlready = array.some(item => item.id === id);
if (!hasRatingAlready) {
updatedArray = [...array, { rating, question, id }];
} else {
updatedArray = array.map(item => item.id === id ? {...item, rating} : item);
}
this.setState({ ratingResponses: updatedArray });

Return a modified new object from a function

what is the best practice to modify and return a new object from a function?
I wrote the following function :
export const addItemToCart = (currentCart, item) => {
const { name, ...otherProps } = item;
//if item exist in the cart
if (currentCart[name]) {
currentCart[name]["quantity"]++;
return currentCart;
}
//if the item does not exist
else
{
currentCart[name] = { ...otherProps };
currentCart[name]["quantity"] = 1;
return currentCart;
}
// the function must return a new modified object on each call
};
Obviously, the hard-coded property "quantity", and the return statements can definitely be improved.
how can I improve this function to be more readable?
More "readable" is very opinion-based, either way, you can try something like this:
const currentCart = {
hello: {
quantity: 1
}
};
const addItemToCart = (currentCart, item) => {
const { name } = item;
// Short circuit + return the last value
const quantityPrev = currentCart[name] && currentCart[name].quantity;
// Or operator on boolean expression
const quantity = 1 + (quantityPrev || 0);
// Destructing for shallow copy, dynamic key assign
return { ...currentCart, [name]: { quantity } };
};
console.log(addItemToCart(currentCart, { name: 'hello' }));
console.log(addItemToCart(currentCart, { name: 'blazer' }));

React: .map is not a function

So I am fairly new to react and most of my learning have been by watching tutorial, So at this point, I diverted from my instructor and started implementing it using my own understanding and then I was thrown with following error
React: .map is not a function
Here is the code
render() {
let person = null;
if (this.state.showPerson) {
person= (
<div>
{
this.state.person.map((el, index) => {
return <Person
key={el.id}
click={this.deletePersonHandler.bind(index)}
name={el.name}
age={el.age}
changed={(event) => this.eventSwitchHandler(event, el.id)} />
})
}
</div>
);
}
return (
The error occured after I implement eventSwitchHandler, Here is my switch handler code
eventSwitchHandler = (event, id) => {
const personInput = this.state.person.find(checkID);
function checkID (passedID) {
return passedID.id === id
}
console.log("newP")
const newP = {...personInput}
console.log(newP)
newP.name = event.target.value
console.log(personInput)
this.setState ({person: newP})
}
[Updated] Here is State
state = {
person: [
{id: "name1n", name: "Rohit", age: 24},
{id: "name2l", name: "Hariom", age: 23},
{id: "name3g", name: "Vaibhav", age: 58}
],
someOtherState: "Untouched state",
showPerson: false
}
[Update] Here is my instructor code, His name change handler is equal to my eventSwitchHandler
Again, My first question would be why does .map is not a function error occurs and while console.logging stuff, I observed something which is kinda rare to me for which I have attached a screenshot (why does the name appear to be different in both the places?)
Your person appears to be a javascript object and not an array which is what provides the map function.
You can check out the rest of the details in the docs here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
To iterate the Object by .map method, utilizing the Object.keys() which returns an array of a given object's keys:
Object.keys(this.state.person).map((key, index) => {
console.log(this.state.person[key]);
})
Update
You have done different things to your instructor code:
eventSwitchHandler = (event, id) => {
const personInput = this.state.person.find(checkID);
function checkID (passedID) {
return passedID.id === id
}
const newP = {...personInput} // **** newP is an object. ****
newP.name = event.target.value
// What you missed:
// let person = this.state.person;
// person[personInput] = newP;
// this.setState ({person: person});
this.setState ({person: newP}) // **** now person becomes object, not an array any more. ****
}
You are not updating the state correctly in eventSwitchHandler
eventSwitchHandler = (event, id) => {
const personInput = this.state.person.find(checkID);
function checkID (passedID) {
return passedID.id === id
}
console.log("newP")
const newP = {...personInput} // newP is an object here
console.log(newP)
newP.name = event.target.value
console.log(personInput)
this.setState ({person: newP}) // overwriting person array with object
}
You would change that to
eventSwitchHandler = (event, id) => {
const personInputIndex = this.state.person.findIndex(checkID);
function checkID (passedID) {
return passedID.id === id
}
const newName = event.target.value
this.setState (prevState => ({
person: [
...prevState.person.slice(0, personInputIndex),
{...prevState.person[personInputIndex], name: newName},
...prevState.person.slice(personInputIndex)
]
})
)
}
or
eventSwitchHandler = (event, id) => {
const personInputIndex = this.state.person.findIndex(checkID);
function checkID (passedID) {
return passedID.id === id
}
const newName = event.target.value
this.setState (prevState => ({
person: Object.assign([], prevState.person, {
[personInputIndex]: {...prevState.person[personInputIndex], newName
}})
})
)
}
eventSwitchHandler = (event, id) => {
const personInput = this.state.person.findIndex(checkID);
function checkID (passedID) {
return passedID.id === id;
}
const person = {...this.state.person[personInput]};
person.name = e.target.value;
const newPerson =[...this.state.person];
newPerson[personInput] = person;
this.setState ({person: newPerson})
}

Update elements of array of object when one element is changed [duplicate]

I've got add
I've got delete
now I need modify
add just adds to the pile haphazardly
delete is able to do it's work with surgical precision because it uses key to find it's culprit :
addInput = (name) => {
const newInputs = this.props.parameters;
newInputs.push({
name,
key: uuid(),
value: { input: '' },
icon: { inputIcon: 0 },
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
removeInput = (key) => {
const newInputs = this.props.parameters.filter(x => x.key !== key);
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
how do I modify (for example set the value back to '' without deleting and recreating the item) ?
modifyInput = (key) => {
?????
};
You can use Array.prototype.find()
modifyInput = (key) => {
const match = this.props.parameters.find(x => x.key === key);
// do stuff with matched object
};
You can map through the parameters and then modify when you find a match:
modifyInput = (key) => {
const newInputs = this.props.parameters.map(x => {
if (x.key === key) {
x.modification = true;
}
return x;
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
var empMap= {};
//initialize empMap with key as Employee ID and value as Employee attributes:
//Now when salary updated on UI from 100 - 300 you can update other fields
var e=empMap[id];
if(e){
e.Salary=newSalary;
e.YearlySalary = newSalary*12;
e.Deductions = e.YearlySalary*0.2;
empMap[id]=e;
}

Categories

Resources