Estoy tratando de usar una matriz vacía en un proyecto react/ts como este. const [companyChatrooms, setCompanyChatrooms]: any = useState([]);
Luego uso un useEffect para hacerlo cuando renderizo el componente.
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.Supongo que tiene una snapshot de matriz con más de 1 elemento y cualquier iteración está actualizando el estado. Esto causó múltiples re-renderizados
Le sugiero que actualice el estado después de iterar toda la matriz. Ejemplo:
const rooms = [] snapshot.forEach(doc => { const roomID = doc.data().chatroom_id; rooms.push(roomID); }); setMyChatrooms(rooms)debe configurarlos todos a la vez.
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)