S
S
Sergey Burduzha2020-08-17 20:09:41
JavaScript
Sergey Burduzha, 2020-08-17 20:09:41

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
    }
  });
}


As you can see, in both functions it differs in the newElem constant like and important.

I decided to make one function and use it.

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);
}


Only, for some reason, the el attribute is not inserted as a property for newElem for me.
5f3ab9ae2e5d7024522743.png

Do not judge strictly, javascript is difficult for me.

Thanks in advance for your reply.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2020-08-17
@serii81

const newElemProps = {
  [el]: !old[el]
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question