react-sortablejs: Warning: Cannot update a component from inside the function body of a different component.

Describe the bug The warning Warning: Cannot update a component from inside the function body of a different component. appears with the latest React version 16.13 when using the example provided in the readme file.

To Reproduce Steps to reproduce the behavior: Create a new component using the example code with React v16.13.0

Expected behavior No warning 😃

Information This happens because the setList method is passed to the child component which results now in a warning.

More information in the react release notes: https://reactjs.org/blog/2020/02/26/react-v16.13.0.html

Versions react-sortable = ^2.0.11 react = ^16.13.0

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 6
  • Comments: 18

Most upvoted comments

This is because ReactSortable is compiled into a function that explicitly calls

props.setList(newList, _this.sortable, store);

If this was source code, wrapping this call with useEffect would fix the issue:

useEffect(() => { props.setList(newList, _this.sortable, store); }, []);

Bad news is that according to https://github.com/facebook/react/issues/18178#issuecomment-592662192 this error may break the whole ReactSortable component in the nearest future…

I’ll still address the issue. It’s becoming obvious that setlist shouldn’t be called within the constructor

Maybe not the best solution, but adding a setTimeout solves it for me for now.

<ReactSortable
  list={items}
  setList={(nextItems) => setTimeout(() => setItems(nextItems))}
>
  {items.map((item) => (
    <Item key={item.id} {...item} />
  ))}
</ReactSortable>

https://codesandbox.io/s/sweet-varahamihira-zdb19