Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 70894

How to save/reload the state of `ion-reorder-group`?

$
0
0

The docs for IonReorderGroup give this code:

import React, { useState } from 'react';
import { IonItem, IonLabel, IonList, IonReorder, IonReorderGroup, ItemReorderEventDetail } from '@ionic/react';

function Example() {
  const [items, setItems] = useState([1, 2, 3, 4, 5]);

  function handleReorder(event: CustomEvent<ItemReorderEventDetail>) {
    // Before complete is called with the items they will remain in the
    // order before the drag
    console.log('Before complete', items);

    // Finish the reorder and position the item in the DOM based on
    // where the gesture ended. Update the items variable to the
    // new order of items
    setItems(event.detail.complete(items));

    // After complete is called the items will be in the new order
    console.log('After complete', items);
  }

  return (
    <IonList>
      {/* The reorder gesture is disabled by default, enable it to drag and drop items */}
      <IonReorderGroup disabled={false} onIonItemReorder={handleReorder}>
        {items.map((item) => (
          <IonItem key={item}>
            <IonLabel>Item {item}</IonLabel>
            <IonReorder slot="end"></IonReorder>
          </IonItem>
        ))}
      </IonReorderGroup>
    </IonList>
  );
}
export default Example;

In my app, I want to let users rearrange items in a certain order, and I want to save the state to my server.

I’m using react-hook-form and I can do that pretty easily.

But, how do I set the initial state of IonReorderGroup? For example, say the user previously updated the state of items to [5,4,3,2,1]; how do I get IonReorderGroup to show the items in that order when the component is loaded?

The problem is that you can’t just change the line const [items, setItems] = useState[5,4,3,2,1] like you would normally set state in React. It seems to be that you need to do something like a one-time useEffect() on component load and then manually trigger handleReorder(), but I’m having trouble getting that to work.

4 posts - 2 participants

Read full topic


Viewing all articles
Browse latest Browse all 70894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>