0

Im new to React Native and i'm still learning so bear with me. I'm getting some data back from the firestore database and I want to transform the data into a new structure so that it can be rendered on the UI in a section list.

useLayoutEffect(() => {
    getEntries()
      .then((newData) => {
        const result = newData.reduce((accum, current) => {
          let dateGroup = accum.find((x) => x.monthYear === current.monthYear);
          if (!dateGroup) {
            dateGroup = { monthYear: current.monthYear, entries: [] };
            accum.push(dateGroup);
          }
          dateGroup.entries.push(current);
          return accum;
        });
        setJournalEntries(result);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

It returns this error:

[TypeError: accum.find is not a function. (In 'accum.find(function (x) {
            return x.monthYear === current.monthYear;
          })', 'accum.find' is undefined)]

I want to reduce the data so that all the journal entries with the same dates are grouped together. I'm thinking that this has something to do with the fact that the data from the database is coming asynchronously to my program, so the data from firestore isn't available once I'm trying to manipulate it. I just don't know how to overcome this. Any suggestions?

  • _"Is this possible?"_ absolutely. You can also reduce an empty array without any problems. Please [edit] your question to include the error message, in full – Phil Jan 25 '23 at 00:29
  • Perform your _reduce_ operation on the `newData` **before** you set it into state. Right now, your _reduce_ only runs once before the data has been retrieved – Phil Jan 25 '23 at 00:33
  • I added the full error and tried to reduce the newData before setting it to state and I'm still receiving an error saying that the data is undefined. – Bailie Richard Jan 26 '23 at 03:42

0 Answers0