Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore freaking out

I just opened my project under another domain (the production url) and when I opened the network requests I saw this:

https://i.imgur.com/NxgTmIf.mp4

This took forever (8 min or more.) and my CPU was hot like hell, What did I do wrong?

My app is quite simple, I suspect the root of this is this block of code:

  const [items, setItems] = useState([]);

  const publish = async () => {
    const batch = firestore.batch();

    items.forEach(({ id }, index) => {
      batch.update(firestore.collection('v1').doc(id), { '#': index });
    });

    await batch.commit();
  };

  const onCompletion = querySnapshot => {
    const arr = [];

    querySnapshot.forEach(document => {
      const { vid: { id: vid }, '#': index } = document.data();

      const { id } = document;

      arr.push({ id, vid, index });
    });

    setItems(arr);
  };

  useEffect(() => {
    const unsubscribe = firestore
      .collection('v1')
      .orderBy('#')
      .onSnapshot(onCompletion);

    return () => {
      unsubscribe();
    };
  }, []);

  useEffect(() => { publish(); }, [items]);

  const handleSortEnd = ({ oldIndex, newIndex }) => {
    if (oldIndex === newIndex) {
      return;
    }

    setItems(arrayMove(items, oldIndex, newIndex));
  };

Basically what this does is load a list of videos from a playlist on a firestore's collection then after the user add a new video or move up/down save again.

Any clues?

Edit: after this madness the app does few requests and works as expected.

like image 267
Rodrigo Avatar asked May 21 '19 14:05

Rodrigo


1 Answers

There's multiple trips to loading your state I think, which by principle should be updated. Why not sort your incoming snapshot as desired before committing it to state. Give a condition to only do the sorting when 'items' has expected values.

Another way is 'setItems' as is from firestore and do sorting of data during the rendering of the state instead of hitting state before rendering.

Moreover, setting a new set of data to your state every time you sort it is mutation. React will take them as new data from before rendering which is not efficient.

like image 198
Niyi Aromokeye Avatar answered Sep 27 '22 17:09

Niyi Aromokeye