Answer the question
In order to leave comments, you need to log in
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 newArray
return {
data = newArray
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question