1

In my code there is a list of groups (which are accordions), this list can be ordered with Drag and Drop. However, to save this information in the database, I need to perform calculations with a 'pos' property

I created a code to get the onDragEnd event from DragDropContext

  const handleDragEnd = (result) => {
    if (!result.destination) {
      return;
    }

    const reorderedList = handleListOrder({ list: groups, result });
    const { newList, reorderedItem } = reorderedList;

    setGroups(newList);

    updateOrderPosition({ id: reorderedItem.id, pos: parseInt(reorderedItem.pos, 10), type: 'originGroup' });
  };

my problem is in the handleListOrder function, because it doesn't return the correct 'pos' values, sometimes they come the same, sometimes smaller or larger than they should be. I would like ideas to solve this problem.

const handleListOrder = ({ list, result }) => {
  const itemsCopy = [...list].map((group, i) => {
    // If the item has a position, keep it, otherwise assign a new position based on index
    const pos = group.pos !== 0 && group.pos !== null && group.pos !== undefined ? group.pos : i * 65535;

    return {
      ...group,
      pos,
    };
  });

  const [reorderedItem] = itemsCopy.splice(result.source.index, 1);
  itemsCopy.splice(result.destination.index, 0, reorderedItem);

  // Calculate the new position of the moved item
  const prevPosition = result.destination.index > 0 ? itemsCopy[result.destination.index - 1].pos : 0;
  const nextPosition = result.destination.index < itemsCopy.length - 1 ? itemsCopy[result.destination.index + 1].pos : prevPosition + 65535 * 2;

  reorderedItem.pos = (prevPosition + nextPosition) / 2;

  return { newList: itemsCopy, reorderedItem };
};

export {
  handleListOrder,
};

I tried to use new logics to solve the problem, but I was not successful. the changes are correctly saved locally due to the library's operation itself, but I can't save it correctly in my database

0 Answers0