I have a simple chat, and I want to show the user only these chats to which he is subscribed.
The database is on Firebase, and the Frontend is React.
First, I add all rooms to room state, and this is saving ok. Then I want to filter these rooms to find only rooms with the user name.
Here I have a problem: I want to save all room with its data (message, name, other users) to new state userRooms.
I have tried different ways, but none of them works.
Docs in db:
collection (rooms) -> docs (name, users<Array>, messages)
The variable user.displayName is a variable with name user from context API after the user signs in.
Code:
const Sidebar = () => {
const [rooms, setRooms] = useState([])
const [userRooms, setUserRooms] = useState([])
const [{ user, active, color, usersList }, dispatch] = useStateValue();
useEffect(() => {
const unsubscribe = db.collection('rooms').onSnapshot(snapshot => (
setRooms(
snapshot.docs.map(doc => ({
id: doc.id,
name: doc.data().name,
users: doc.data().users
}))
)
))
return () => {
unsubscribe();
};
}, [])
// try with map and filter
useEffect(() => {
rooms.map(room => {
room.users.filter(item => item === user.displayName)
return setUserRooms({
...userRooms,
room
})
}
)
}, [rooms])
// try with filter from filter here room in setUserRooms is unknown
useEffect(() => {
rooms.filter(room => room.users.filter(item => item === user.displayName))
.map(
setUserRooms({...userRooms, room})
)
}, [rooms])
// try with includes but show includes is undefined
useEffect(() => {
rooms.filter(room => room.users.includes(user.displayName) && setUserRooms(...userRooms, room))
}, [rooms])
// check with if but it even doesn't work
useEffect(() => {
rooms.filter(room => {
if(room.users === user.displayName) setUserRooms(prev => [...prev, room])
})
}, [rooms])