Answer the question
In order to leave comments, you need to log in
How to insert an attribute from a function into an object property?
Good afternoon.
Started learning React and ran into a problem.
There are two functions, one adds likes, the other stars for ratings.
this.onToggleLike = (id) => {
this.setState(({data}) => {
const index = data.findIndex(elem => elem.key === id);
const old = data[index];
const newElem = {...old, like: !old.like};
const newArr = [...data.slice(0, index), newElem, ...data.slice(index + 1)];
return {
data: newArr
}
});
}
this.onToggleImportant() = (id) => {
this.setState(({data}) => {
const index = data.findIndex(elem => elem.key === id);
const old = data[index];
const newElem = {...old, important: !old.important};
const newArr = [...data.slice(0, index), newElem, ...data.slice(index + 1)];
return {
data: newArr
}
});
}
this.toggleElemInData = (el, id) => {
this.setState(({data}) => {
const index = data.findIndex(elem => elem.key === id);
const old = data[index];
const newElemProps = {
el: !old[el]
};
const newElem = {...old, ...newElemProps};
const newArr = [...data.slice(0, index), newElem, ...data.slice(index + 1)];
return {
data: newArr
}
});
}
this.onToggleImportant = (id) => {
this.toggleElemInData('important', id);
}
this.onToggleLike = (id) => {
this.toggleElemInData('like', id);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question