Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
useState array becomes 2 arrays in console.log?

Im trying to just use a empty array in a react/ts project like this. const [companyChatrooms, setCompanyChatrooms]: any = useState([]);

I then use a useEffect to get it done when rendering component.

    async function fetchMyChatRooms() {
    const userCollection = await firestore.collection('user_in_chat')
    const snapshot = await userCollection.where('user_id', '==', myIdNumber).where('chatroom_id', '==', companyChatrooms).get();
    snapshot.forEach(doc => {
    const roomID = doc.data().chatroom_id
    setMyChatrooms([...myChatrooms, roomID])
    });
    }
    fetchMyChatRooms()
    }, [companyChatrooms, myIdNumber])
    console.log(myChatrooms)```

However, my console.log shows 2 arrays with each value instead of 1 array holding both values.

How can i make sure both values are stored in same array?


  [1]: https://i.stack.imgur.com/q0WPD.png  <-- Check how the output looks.
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I assume you have an array snapshot with more than 1 element and any iteration you are updating the state. This caused multiple re-render

I suggest you to update state after iterate entire array. Example:

const rooms = []
snapshot.forEach(doc => {
    const roomID = doc.data().chatroom_id;
    rooms.push(roomID);
});
setMyChatrooms(rooms)
about 4 years ago · Juan Pablo Isaza Denunciar

0

you should set all of them in one time.

   async function fetchMyChatRooms() {
    const userCollection = await firestore.collection('user_in_chat')
    const snapshot = await userCollection.where('user_id', '==', myIdNumber).where('chatroom_id', '==', companyChatrooms).get();
   
// here is the changing
const roomIDs = snapshot.map(doc => doc.data().chatroom_id);
setMyChatrooms(roomIDs )
//
  fetchMyChatRooms()
    }, [companyChatrooms, myIdNumber])
    console.log(myChatrooms)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda