react-sortablejs icon indicating copy to clipboard operation
react-sortablejs copied to clipboard

Loading State from store.get

Open omeiirr opened this issue 4 years ago • 5 comments

Context: I have a grid of images whose order can be changed by the user. I want to save the modified order and have it accessible so that it persists on a page refresh or when the user revisits the form. Ideally, the order should be communicated to the server and loaded from the server as well, but currently the 'get' method is not working even with the localStorage, as described in the store documentation.

image

Problem: I tried the get and set methods from 'store', but only the set seems to work. Whenever I reorder the images, the localStorage gets updated accordingly, but the images go to their default positions on page refresh.

Key-value pair in localStorage: example : 60b4f506a8ee53a1d8aad392|60b4f506a8ee53a1d8aad394|60b4f506a8ee53a1d8aad393

I tried to use

    sortable.sort(order)

but I'm unsure where to call this.

How can I ensure that the images are positioned according to the positions last set by the user when the page loads?

Any help in this matter is highly appreciated. Thank you for your time.


      <ReactSortable
        list={samples}
        setList={setSamples}
        className="list"
        onEnd={handleEnd}
        delayOnTouchStart={true}
        // delay={50}
        animation={500}
        ghostClass="ghost"

        group="example"

        store={{
          get: function (sortable) {
            console.log(sortable);        // even this is not being logged
            var order = localStorage.getItem(sortable.options.group.name);
            return order ? order.split("|") : [];
          },

          set: function (sortable) {
            var order = sortable.toArray();
            console.log(order);
            localStorage.setItem(sortable.options.group.name, order.join("|"));
          },

        }}
      >

omeiirr avatar Jun 02 '21 16:06 omeiirr

Did you figure it out?

2brownc avatar May 28 '23 02:05 2brownc

I don't exactly remember since it's been so long, but I think the solution involved using useEffect to sort the images on page load.

Let me know if it works.

omeiirr avatar May 28 '23 10:05 omeiirr

Thanks for the reply.

The state variable contains the current order of the list and that is what I ended up using.

  const [state, setState] = useState<ItemType[]>([
    { id: 1, name: "shrek" },
    { id: 2, name: "fiona" },
  ]);

2brownc avatar May 29 '23 02:05 2brownc

So it's working as expected now?

omeiirr avatar May 29 '23 03:05 omeiirr

I don't think it's the intended way. But I found a way I guess.

2brownc avatar May 29 '23 07:05 2brownc