Array only update once after setState

Viewed 31

I have a problem trying to update an array in a setState.

First of all, I have an array in the main component called "myCourses", that have the information about the courses from a student. Then, I have a modal component, which opens after a click event. The modal receives "myCourses" from main and modify when some conditions are true, and the array is updated.

The problem occurs after the setStateMyCourses in modal component, because the cards only renders once, after a few intents with the same patron (open the modal, do the same things and the courses not changes visually, when in the first intent the element is removed).

Here I detach some code of the project.

Main component:

const [myCourses, setMyCourses] = useState([]);

UseEffect(() => {
...
loadMyCourses(setMyCourses)
...
},[]);

...
{myCourses.map((item) => {Card name = {item.name}}
...


{condition && <ModalComponent myCourses={myCourses} setMyCourses={setMyCourses}/>}

In ModalComponent I have the following:

...
const myCoursesAux = myCourses

myCoursesAux.splice(index, 1);

setMyCourses([...myCoursesAux]);
...
2 Answers

You should never mutate state directly, instead use the updater function form of setState to modify the array without mutating it. Have a look at this documentation for reference

setMyCourses(prev => prev.filter((_,i) => i !== index))

Sorry for the dealy, and thanks again for the reply. I found the problem yesterday. The problem was in the first condition when I call for the modal component.

Related