Description
I'm using sortablejs in React since I need the handle and nested drag-and-drop list.
Problem: I can't read the newest props when the drag action ends.
Description: This page is for editing purpose. I have a nested 3 level drag and drop list with textarea. like this
I only have an "allItems" state in my parent component and every text change will modify this state and trigger the rerender.
When I finish dragging, the list's order will change, but all the changes I did in the textarea are gone.
I tried to print out the "allItems" in different places, I found out that in store.set, onEnd, onUpdate, and onChange, the data of "allItems" is the initial value, not the newest one.
So I assume that somehow there's a state in my sortable variable and it is not updated.
But I thought that I change the state, trigger the rerender, and my useEffect listen to the "allItems" passed in from parent and create the sortable again, so it should have the newest value?
How can I solve this problem?
Thanks in advance.
Code:
// this function simply print the props "allItems" passed from parent component
// str indicates where I call this function
const test = (str) => {
console.log(allItems, 'in test', str)
}
useEffect(() => {
test('in effect')
// serialNum is a unique number I create from Date.now() to insure el has the newest html element
let el = document.getElementById(`listWithHandle${serialNum}`)
let sortable = Sortable.create(el,{
group: `nested ${serialNum}`,
animation: 500,
fallbackOnBody: true,
swapThreshold: 0.65,
handle: '.glyphicon-move',
onEnd: (evt) => {
test('in on end')
},
store: {
get: function (sortable) {
test('in get')
},
set: (newOrder) => {
updateOrder(allItems, newOrder)
}
}
})
return () => {
// cleanup
}
}, [allItems])
const updateOrder = useCallback((all, newHTMLOrder) => {
test('in update')
... some logic
// update the parent
setListItems(all)
}, [allItems])