SortableJS/react-sortablejs

List rendering not updating with new Set array on props update

Closed this issue · 0 comments

Hi,

I use SortableJS to have a list of reordering "Sources" and what I am trying to achieve, is to be able to update this list with deduplicated Set array.

As you can see below, I have my "Sortable.tsx" component which is controlled by "inst" props and its rendering triggered on "useEffect" in order to build the new Set array having no duplicate "Sources".

import { ReactSortable } from "react-sortablejs";

import type { InstSelectProps } from "./InstSelect";
import { getSourceItemsById } from "@/domain/sources";

import type { SourceItem } from "@/domain/sources/source.type";

export type SortableItem = Omit<SourceItem, "name"> & {
  name: string;
};

export default ({ inst }: Pick<InstSelectProps, "inst">) => {
  const [sources, setSources] = useState<SortableItem[]>([]);

  useEffect(() => {
    if (inst) {
      const instSources: SortableItem[] =
        getSourceItemsById(inst.sources) ?? [];
      setSources((prev) => [...new Set([...prev, ...instSources])]);
    }
  }, [inst]);

  return (
   <ReactSortable list={sources} setList={setSources}>
      {[...sources].map(({ id, name }) => (
        <div key={id}>{name}</div>
      ))}
    </ReactSortable>
  );
};

The problem is I don't see why the new list isn't deduplicated (with new Set(...)) before the update rendering, and I keep having duplicated "Sources" ?

Image

Thanks for your help