A
A
Anton2020-06-25 17:09:26
React
Anton, 2020-06-25 17:09:26

How to update a component when the state changes?

There is a component

function Tasks(tasksData) {
    return (
        <React.Fragment>
            tasksData.map((task) => (
                <Task
                    key={task.ID}
                    task={task}
                />)
            )
        </React.Fragment>
    )
}


Further, all actions are performed in the component, and after this task, which is passed inside the component, is removed from the state, i.e. if earlier there was state.tasksData[task0, task2, ..., task10], then later it became state.tasksData[task0, task2, ..., task9].
And that's the question, in Redux DevTools I see that the necessary actions have passed, and the necessary task has been removed from our state, but the Tasks component still displays the Task, which is no longer in the state.
How to make it so that when the task is removed from the state, the page is re-rendered with the new state?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-06-25
@zakharoffam

The first rule of Redux is to always spread a mutable value, otherwise redux doesn't know you've changed it. The splice method you are using does not change the array, and map is meaningless in this case. The correct code would be:

const index = state.tasksData.findIndex(({ ID }) => ID === payload.ID)
if (index > -1) return {
  ...state,
  tasksData: 
    state.tasksData.slice(0, index).concat(
      state.tasksData.slice(index + 1))
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question