Home > Net >  Cannot map array using getDocs to read data for a Flatlist
Cannot map array using getDocs to read data for a Flatlist

Time:08-16

I have an Expo project with this code to retrieve a collection from Firestore:

import { getFirestore, collection, getDocs } from 'firebase/firestore';

const firebaseConfig = {...};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);


const HomeScreen = ({navigation}) => {

  const [events, setEvents] = useState([]);
  
  useEffect(() => {
    const getEvents = async (dbx) => {
      const eventsCol = collection(dbx, 'testing');
      const eventSnapshot = await getDocs(eventsCol);
      const eventList = eventSnapshot.docs.map((doc) => 
        ({
          ...doc.data(),
          key: doc.id
        })
      );
      console.log("Event list inside: ",eventList);
      return eventList;
    }
    setEvents(getEvents(db));
    console.log("Events: ",events);
}, []);

The console prints this inside the function, which is the array I need to display in a Flatlist.

Event list inside:  Array [
  Object {
    "features": Object {
      "best": "movement",
      "better": "arm",
      "good": "read",
    },
    "height": "1.91",
    "key": "63eM32mC897nvK2ZvdWz",
    "name": "Mahomes",
  },
  Object {
    "features": Object {
      "best": "audibles",
      "better": "arm",
      "good": "pocket",
    },
    "height": "1.98",
    "key": "FavrYCjD1ls56wKOMQPg",
    "name": "Manning",
  },
  Object {
    "features": Object {
      "best": "strength",
      "better": "arm",
      "good": "reads",
    },
    "height": "1.98",
    "key": "eaM8ipLVrn9OEg35SLgk",
    "name": "Herbert",
  },
]

But after calling setEvents I get this structure which of course won't work with FL

    Events:  Promise {
  "_U": 0,
  "_V": 1,
  "_W": Array [
    Object {
      "features": Object {
        "best": "movement",
        "better": "arm",
        "good": "read",
      },
      "height": "1.91",
      "key": "63eM32mC897nvK2ZvdWz",
      "name": "Mahomes",
    },
    Object {
      "features": Object {
        "best": "audibles",
        "better": "arm",
        "good": "pocket",
      },
      "height": "1.98",
      "key": "FavrYCjD1ls56wKOMQPg",
      "name": "Manning",
    },
    Object {
      "features": Object {
        "best": "strength",
        "better": "arm",
        "good": "reads",
      },
      "height": "1.98",
      "key": "eaM8ipLVrn9OEg35SLgk",
      "name": "Herbert",
    },
  ],
  "_X": null,
}

I can't find any documentation or examples and I'm kind of new to React-Native, any hints or ideas?

CodePudding user response:

Instead of calling

setEvents(getEvents(db));

call only

getEvents(db)

and within your getEvents function call

setEvents(eventList)

this way you're setting the events state variable to be the mapped data instead of the function call, which appears to be returning the entire Promise instead of just the response.

  • Related