0

I'm using this drag and drop library to be able to reorder a list of articles on my page: https://github.com/atlassian/react-beautiful-dnd

However, even though I'm able to drag them up and down and re-order them, when I refresh the page they go back to their initial state.

The articles are pulled from Cloud Firestore.

How can I make them maintain the new order each time I move things around?

class Articles extends Component {
  constructor(props) {
    super(props);
    this.ref = firebase.firestore().collection("articles");
    this.unsubscribe = null;
    this.onDragEnd = this.onDragEnd.bind(this);
    this.state = {
      articles: [],
    };
  }

  onCollectionUpdate = (querySnapshot) => {
    const articles = [];
    querySnapshot.forEach((doc) => {
      const { title } = doc.data();
      articles.push({
        key: doc.id,
        title,
      });
    });
    this.setState({
      articles,
    });
    this.onDragEnd = this.onDragEnd.bind(this);
  };

  componentDidMount() {
    this.unsubscribe = this.ref.onSnapshot(this.onCollectionUpdate);
  };

  onDragEnd(result) {
    if (!result.destination) return;
        
    const items = this.state.articles;
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    this.setState(items)
  } 

Then in my return(), I've got something like:

<DragDropContext onDragEnd={this.onDragEnd}> ... />
Ken White
  • 123,280
  • 14
  • 225
  • 444
cldev
  • 671
  • 8
  • 18

1 Answers1

0

You are fetching data from a remote source. So u need to update that remote source after reordering. You have to do this inside onDragEnd function. Currently you are only updating your local state with this.setState(items). That's why you lose your reorder on page refresh.

miraj
  • 546
  • 3
  • 12
  • I think this makes a bit of sense, sorry I'm new to this! So inside the onDragEnd, I should do the update document just like here: https://firebase.google.com/docs/firestore/manage-data/add-data ??? – cldev Feb 17 '21 at 23:16
  • You can use `this.ref.update(items)` inside the `onDragEnd()` https://firebase.google.com/docs/firestore/manage-data/add-data#update-data – miraj Feb 18 '21 at 00:52