Home > front end >  How to push Firebase collection in Array to get list
How to push Firebase collection in Array to get list

Time:12-16

Hello i'm a beginner in React Native and firebase,

const [event, setEvent] = useState([]);
const myEvents = () => {
        db.orderBy('dateEvent', 'desc').get().then((querySnapshot) => {
            querySnapshot.docs.map(snapshot => {
                event.push(snapshot.data())
            })
        })
        setEvent(event)
    }
    useEffect(() => {
        myEvents();
        console.log(event)
    }, [])
}

Through the log, I have this : enter image description here

When I try to get the first index with console.log(event[0]) the result is undefined

And when I try this through this sample data :

const DATA = [
  {
    id: "1",
    title: "Test1",
  },
  {
    id: "2",
    title: "Test2",
  },
];
console.log(DATA)

I got this enter image description here

And it return the object with DATA[0]

These list aren't look the same format, I don't know how can I do my event List like the DATA List and get for the event a log like [{obj},{obj},{obj}] and not [].

Sorry if there's some fault

CodePudding user response:

Try to store this way:

const [event, setEvent] = useState([]);

const myEvents = () => {
        db.orderBy('dateEvent', 'desc').get().then((querySnapshot) => {
            querySnapshot.docs.map(snapshot => {
                let sample = event
                sample.push(snapshot.data())
                setEvent(sample)
            })
        })
        
    }
    useEffect(() => {
        myEvents();
        console.log(event)
    }, [])
}

CodePudding user response:

All the code

const DATA = [
        {
          id: "1",
          title: "First Item",
        },
        {
          id: "2",
          title: "Second Item",
        },

      ];

      console.log(DATA)

    const [selectedId, setSelectedId] = useState(null);
    const [event, setEvent] = useState([]);
    const [selectedEvent, setSelectedEvent] = useState(null);

    const myEvents = () => {
        db.orderBy('dateEvent', 'desc').get().then((querySnapshot) => {
            querySnapshot.forEach(snapshot => {
                let sample = event
                event.push(snapshot.data())
                setEvent(sample)
            })
        })
        
    }
    useEffect(() => {
        myEvents();
        console.log('just event',event)
        console.log('with event[0]',event[0])
    })

the log

enter image description here

  • Related