reactjsreact-hooksreact-sortable-hoc

How to make the state update in React with the last added task?


I am building a simple todo app and after I have implemented react-sortable-hoc - which if you dont know is a plugin for react that implements drag and drop - the todos list doesnt update with the last added todo anymore. I dont get any kind of error in the console.

I tried to use the state that is sorted in the react-sortable-hoc onSortEnd function, but then I get Invalid attempt to spread non-iterable instance error.

This is the application an codesandbox

I want to make the state update with the lattest added todos.


Solution

  • Your code has 2 issues that I can see:

    1) In Form.js, you are not actually setting the state to the new array which contains the latest value when the form submits. In your handleSubmit function you'd need to call setState(createNewTask(value)) rather than just createNewTask(value).

    2) You are using a separate piece of state called alteredState to actually create your list and initializing it with the tasks array in your main state. However, you are not updating this second array when the primary array is changed, as the value passed into useState is only set once on mount. You can use a useEffect hook to update your secondary state when the first is changed:

    useEffect(() => {
        setAlteredState(state.tasks);
      }, [state]);
    

    Fork here.