How do I load sub array from Realtime Database using React?

Issue

There are records in real-time DB that have a subarray:
enter image description here

And I’m not sure how do I load it in my hook. I also created the type to receive it in an array.
I found some examples, however, I’m looking for a way to do it easier.

type EventType = {
    id: string,
    autorID: string,
    autorNome: string,
    titulo: string,
    categoria: string,
    dateS: string,
    dateE: string,
    descricao: string,
    cancelado: string,
    confirmCount: number,
    confirmadosList: Record<string,{
        confirmedByUserID: string,
        confirmedByUserName: string,
        confirmedByUserAvatar: string
    }>
}

useEffect(()=>{
        const eventRef = database.ref(`eventos/${eventID}`)

        eventRef.once('value', evento =>{
            //console.log(evento.val());
            const eventValue = evento.val();

            const vari:EventType = {
                id: eventValue.key,
                autorID: eventValue.authorID,
                autorNome: eventValue.authorName,
                titulo: eventValue.title,
                categoria: eventValue.category,
                dateS: eventValue.startDate,
                dateE: eventValue.endDate,
                descricao: eventValue.description,
                cancelado: eventValue.canceled,
                confirmCount: eventValue.confirmados.length,
                confirmadosList: {
                    
                }
            }

            setEvento(vari)
            
            //setCountConfirm(Object.values(eventValue.confirmados ?? {}).length)
            //setHasConfirm(Object.values(eventValue.confirmados ?? {}).some(confirmado => confirmado.confirmedByUserID === user?.id))
        })
    },[eventID])

Solution

The confirmados node in your database is a Map, not a list. While you can get just the values of the keys under confirmados, that means you’re throwing away the keys themselves.

If that is what you want, it’d be:

eventRef.once('value', snapshot =>{
  ...
  const confirmadosValues = [];
  snapshot.child('confirmados').forEach((confirmado) => {
    confirmadosValues.push(confirmadosValues.val());
  });
  ...

If you only want the value of confirmedByUserID, that inner line would be:

confirmadosValues.push(confirmadosValues.val().confirmedByUserID);

Answered By – Frank van Puffelen

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.