A
A
Arthur2019-06-03 19:59:40
React
Arthur, 2019-06-03 19:59:40

What does return return?

Good evening programmers.
I just trained in react. and I had a situation when, after processing, it was necessary to return an object for rendering.
The data enters the state after destructuring in the following form:

this.setState(({ data }) => {
       const idx = data.findIndex((el) => el.id === id);
       const before = data.slice(0, idx);
       const after = data.slice(idx + 1);
       const newArray = [...before, ...after]
        return {
            data: newArray
        }
      } )

return returns this todoData: newArray
I can't figure out why this is the syntax?
At the beginning, I wrote just
return newArray
gave an error. Then I thought that return should return an object and wrote like this
return {
            data = newArray
        }

That didn't work either....why do you need to return data: newArray in this form?
Thank you for your responses.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-06-03
@TurnerIT

The function passed as the first argument to setState in class components must return an object that updates some properties of the state object. In your case, this is an object containing the data property. In your examples, in the first case an array was returned, in the second there was invalid code.
Your state update code can be shortened to:

this.setState(state => ({
  data: state.data.filter(el => el.id !== id), 
}));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question