Search code examples
reactjsreact-hookscreate-react-appreact-statereact-state-management

Filtering the state data doesn't work fine - React (CRA)


I have created a simple todo application. I can add items to the todo, and filter the list through all, completed and incomplete. All the lists are rendered respectively. The problem is when I am any of the completed or incomplete filters, and I check or uncheck the task respectively, the list should be filtered again on each check/uncheck. I am able to call the filter method, but having some unexpected behavior of the state, it removes the list elements except that I check/uncheck when any of the filters are active.

I have created this sandbox, play around it.

Sanbox


Solution

  • I think your problem is that when you check an item, in modifyList you are setting copiedList to the previous state of list, which is a filtered subset of the entire data. changing setList to setCopiedList seems to have solved the issue for me.

    const modifyList = (list) => {
      setCopiedList((prevState) => {
        let state = [...prevState];
        return state;
      });
    };