Paginating firestore data with realtime additions on top of the result - javascript

I want to load my data into chunks of 10 in react. I am listening for document addition using onSnapshot() firestore method. I want to paginate data and at the same time allow the recent addition to come to the top. How to apply this in the code below -
db.collection('palettes').orderBy("createdAt").onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
if (change.type === "added") {
setPalette( prevPalette => ([
{ id: change.doc.id, ...change.doc.data() },
...prevPalette
]))
setIsLoading(false)
}
})
})

I think you should save state of last document for pagination and realtime updates
Example
const getPalettes = (pageSize, lastDocument) => new Promise((resolve, reject) => {
let query = db.collection('palettes')
.orderBy("createdAt")
if(lastDocument) {
query = query.startAt(lastDocument)
}
query = query.limit(pageSize);
return query.onSnapshot(query => {
const docs = query.docs.map(pr => ({pr.id, ...pr.data()}))
resolve(docs);
});
})
let unsubscribe = getPalettes(10).then(newPalettes => {
setPalette(palettes => [...palettes, newPalettes]);
lastPalette = newPalettes[newPalettes.length -1];
setLastPalette(lastPalette);
unsubscribe();
})
unsubscribe = getPalettes(10, lastPalette).then(newPalettes => {
setPalette(palettes => [...palettes, newPalettes]);
lastPalette = newPalettes[newPalettes.length -1];
setLastPalette(lastPalette);
unsubscribe();
})
const listenForLatestPalettes = (lastDocument, callback) => {
return db.collection('palettes')
.orderBy("createdAt")
.startAt(lastDocument)
.onSnapshot(callback);
}
const callback = snapshot => {
for(let change of snapshot.docChanges()) {
if (change.type === "added") {
setPalette(palettes => {
const palette = { id: change.doc.id, ...change.doc.data() };
return [...palettes.filter(pal => pal.id !== id], palette];
})
}
}
}
unsubscribe = listenForLatestPalettes(lastDocument, callback);

Related

Trying to figure out how to use socket.io the correct way in a useEffect that is using an axios get request to fetch messages

So far i'm stuck on my useEffect that fetches all the current messages and renders the state accordingly. as of right now it doesn't render the new state until page is refreshed.
const Home = ({ user, logout }) => {
const history = useHistory();
const socket = useContext(SocketContext);
const [conversations, setConversations] = useState([]);
const [activeConversation, setActiveConversation] = useState(null);
const classes = useStyles();
const [isLoggedIn, setIsLoggedIn] = useState(false);
const addSearchedUsers = (users) => {
const currentUsers = {};
// make table of current users so we can lookup faster
conversations.forEach((convo) => {
currentUsers[convo.otherUser.id] = true;
});
const newState = [...conversations];
users.forEach((user) => {
// only create a fake convo if we don't already have a convo with this user
if (!currentUsers[user.id]) {
let fakeConvo = { otherUser: user, messages: [] };
newState.push(fakeConvo);
}
});
setConversations(newState);
};
const clearSearchedUsers = () => {
setConversations((prev) => prev.filter((convo) => convo.id));
};
const saveMessage = async (body) => {
const { data } = await axios.post("/api/messages", body);
return data;
};
const sendMessage = (data, body) => {
socket.emit("new-message", {
message: data.message,
recipientId: body.recipientId,
sender: data.sender,
});
};
const postMessage = async (body) => {
try {
const data = await saveMessage(body);
if (!body.conversationId) {
addNewConvo(body.recipientId, data.message);
} else {
addMessageToConversation(data);
}
sendMessage(data, body);
} catch (error) {
console.error(error);
}
};
const addNewConvo = useCallback(
(recipientId, message) => {
conversations.forEach((convo) => {
if (convo.otherUser.id === recipientId) {
convo.messages.push(message);
convo.latestMessageText = message.text;
convo.id = message.conversationId;
}
});
setConversations(conversations);
},
[setConversations, conversations],
);
const addMessageToConversation = useCallback(
(data) => {
// if sender isn't null, that means the message needs to be put in a brand new convo
const { message, sender = null } = data;
if (sender !== null) {
const newConvo = {
id: message.conversationId,
otherUser: sender,
messages: [message],
};
newConvo.latestMessageText = message.text;
setConversations((prev) => [newConvo, ...prev]);
}
conversations.forEach((convo) => {
console.log('hi', message.conversationId)
if (convo.id === message.conversationId) {
const convoCopy = { ...convo }
convoCopy.messages.push(message);
convoCopy.latestMessageText = message.text;
console.log('convo', convoCopy)
} else {
return convo
}
});
setConversations(conversations);
},
[setConversations, conversations],
);
const setActiveChat = useCallback((username) => {
setActiveConversation(username);
}, []);
const addOnlineUser = useCallback((id) => {
setConversations((prev) =>
prev.map((convo) => {
if (convo.otherUser.id === id) {
const convoCopy = { ...convo };
convoCopy.otherUser = { ...convoCopy.otherUser, online: true };
return convoCopy;
} else {
return convo;
}
}),
);
}, []);
const removeOfflineUser = useCallback((id) => {
setConversations((prev) =>
prev.map((convo) => {
if (convo.otherUser.id === id) {
const convoCopy = { ...convo };
convoCopy.otherUser = { ...convoCopy.otherUser, online: false };
return convoCopy;
} else {
return convo;
}
}),
);
}, []);
// Lifecycle
useEffect(() => {
// Socket init
socket.on("add-online-user", addOnlineUser);
socket.on("remove-offline-user", removeOfflineUser);
socket.on("new-message", addMessageToConversation);
return () => {
// before the component is destroyed
// unbind all event handlers used in this component
socket.off("add-online-user", addOnlineUser);
socket.off("remove-offline-user", removeOfflineUser);
socket.off("new-message", addMessageToConversation);
};
}, [addMessageToConversation, addOnlineUser, removeOfflineUser, socket]);
useEffect(() => {
// when fetching, prevent redirect
if (user?.isFetching) return;
if (user && user.id) {
setIsLoggedIn(true);
} else {
// If we were previously logged in, redirect to login instead of register
if (isLoggedIn) history.push("/login");
else history.push("/register");
}
}, [user, history, isLoggedIn]);
useEffect(() => {
const fetchConversations = async () => {
try {
const { data } = await axios.get("/api/conversations");
setConversations(data);
} catch (error) {
console.error(error);
}
};
if (!user.isFetching) {
fetchConversations();
}
}, [user]);
const handleLogout = async () => {
if (user && user.id) {
await logout(user.id);
}
};
return (
<>
<Button onClick={handleLogout}>Logout</Button>
<Grid container component="main" className={classes.root}>
<CssBaseline />
<SidebarContainer
conversations={conversations}
user={user}
clearSearchedUsers={clearSearchedUsers}
addSearchedUsers={addSearchedUsers}
setActiveChat={setActiveChat}
/>
<ActiveChat
activeConversation={activeConversation}
conversations={conversations}
user={user}
postMessage={postMessage}
/>
</Grid>
</>
);
};
this is the main part im working on, the project had starter code when i began and was told not to touch the backend so i know its something wrong with the front end code. i feel like im missing something important for the socket.io
import { io } from 'socket.io-client';
import React from 'react';
export const socket = io(window.location.origin);
socket.on('connect', () => {
console.log('connected to server');
});
export const SocketContext = React.createContext();
this is how i have the socket.io setup, if anyone could point me in the right direction that would be cool. I have been reading up on socket.io as much as I can but am still pretty lost on it.
Based on the assumption the backend is working properly...
const addNewConvo = useCallback(
(recipientId, message) => {
conversations.forEach((convo) => {
if (convo.otherUser.id === recipientId) {
convo.messages.push(message);
convo.latestMessageText = message.text;
convo.id = message.conversationId;
}
});
setConversations(conversations);
},
[setConversations, conversations],
);
setConversations(conversations);
This is an incorrect way to set a state using the state's variable, and such it wont do anything. Likely why your code wont change until refresh.
Suggested fix:
const addNewConvo = useCallback(
(recipientId, message) => {
setConversations(previousState => previousState.map(convo => {
if (convo.otherUser.id === recipientId) {
convo.messages.push(message)
convo.latestMessageText = message.text;
convo.id = message.conversationId;
return convo
}
return convo
}))
},
[setConversations, conversations],
);
note: even above could be done more efficiently since I made a deep copy of messages

how to run useEffect only twice

Here is My useEffect is going in Infinite loop, becouse checkimage value is changing becouse the value is assigned in fetch(), so anyone know how to solve it. I want to get varient data with image but I can't get it in first time.
help me if you can
Thank You
useEffect(() => {
fetch({ pagination });
}, [checkimage]);
const fetch = async (params = {}) => {
if (type == 'product') {
dispatch(await ProductService.getProduct(productId))
.then((res) => {
let variantsdatas = getImageArns(res.data.variants);
getImages(variantsdatas);
let record = [];
record.push(res.data)
setVarientsData(record)
})
.catch((err) => {});
} else {
dispatch(await ProductService.getProducts())
.then((res) => {
console.info({ 'res.data': res.data });
setVarientsData(res.data.products);
setPagination({
...params.pagination,
total: res.total_count,
});
})
.catch((err) => {});
}
};
const getImageArns = (variantsdatas) => {
const variantImageArns = [];
variantsdatas.forEach((variant, index) => {
variant[index] = variant.variantId;
if (variant.variantImagesListResponseDto.images.length > 0) {
let variantImageObj = {
variantId: variant.variantId,
arnUrl: variant.variantImagesListResponseDto.images[0].docUrl,
};
variantImageArns.push(variantImageObj);
}
});
// console.info('id', variantImageArns);
return variantImageArns;
};
const getImages = async (variantsdatas) => {
const images = [];
dispatch(await ProductVariantService.getImage(variantsdatas))
.then((res) => {
console.info(res.data.fileResponseDtoList);
let presignedURLs = {};
res.data.fileResponseDtoList.map(
(i) => (
(presignedURLs = {
variantId: i.variantId,
arnUrl: i.presignedURL,
}),
console.info(presignedURLs),
images.push(presignedURLs)
)
);
setcheckimage(images);
})
.catch((err) => {
console.info('Get Error District...');
});
};
var img = 'img';
const setVarientsData = (products) => {
let varients_array = [];
if (products.length > 0) {
products.forEach((product) => {
if (product.variants.length > 0) {
let product_varients = product.variants;
product_varients.forEach((varient) => {
for (var f = 0; f < checkimage.length; f++) {
if(checkimage[f].variantId == varient.variantId){
img = checkimage[f].arnUrl;
f = checkimage.length
}
else{
img = 'img2';
}
}
varients_array.push({
image: img,
variantId: varient.variantId,
productVariantName: varient.variantName,
productName: product.productName,
brand: '-',
sellerSku: varient.productVariantCode,
status: product.status,
category: product.subCategoryInfo.categoryInfo.categoryName,
subCategoryName: product.subCategoryInfo.subCategoryName,
state: '-',
market: '-',
mrp: varient.price.amount + ' ' + varient.price.currency,
sellingPrice: '-',
manufacturer_product_variant_code:
varient.manufacturerProductVariantCode,
product_varient_code: varient.azProductVariantLongCode,
hsnCode: varient.hsnCode,
});
});
}
});
}
setVarients(varients_array);
console.info('varients_array ====>>', {varients_array})
};
I think that if I stop to run blow code getImage function then I can get my result
am I right?
But I tried It too but is also not happening properly.
a quick and dirty fix could be to work with a counter.
and only run the fetch in the useEffect, when counter is 0.
have you tried that?

Download multiple files from Firebase in ReactJS

I have several folders in firebase storage that contain images (each folder corresponds to an entity).https://i.stack.imgur.com/s9ZpX.png
When I want to download the url of each entity, what firebase does is bring me all the images that it has in the storage even if it does the forEach to each entity.
useEffect(() => {
setLoading(true);
Promise.all([getRooms(), getLocation()])
.then((values) => {
const roomsSnapshot = values[0];
const rooms = [];
const pUrl = [];
roomsSnapshot.forEach((doc) => {
const splitAddress = doc.data().address.split(", ");
formatedAddress.current = splitAddress[1] + " " + splitAddress[0];
//Download from storage//
storage
.ref(`${doc.data().roomPhotoId}/`)
.list()
.then(function (result) {
result.items.forEach((imageRef) => {
imageRef.getDownloadURL().then((url) => {
console.log(url)
roomItems.push(url)
});
});
setRoomsImagesCounter(roomsImagesCounter + 1);
// no photos scenario
if (result.items.length === 0) {
setLoading(false);
}
});
//pushing entity data//
rooms.push({
...doc.data(),
id: doc.id,
photosURL: roomItems,
shortAddress: formatedAddress.current,
coordsAddress: coords.current,
});
});
console.log(rooms);
setRooms(rooms);
// getPhotos(rooms);
setLoading(false);
})
.catch((err) => {
console.log("Error getting getting rooms or user role", err);
});
// eslint-disable-next-line react-hooks/exhaustive-deps }, []);
I don't know why firebase brings me all the images instead of bringing me the images separately for each entity.
I hope you have understood and I await your answers or any questions you have.
Thanks!
UPDATE
This is the console.log(rooms) https://i.stack.imgur.com/rQkoB.png
Can you try to create the storage ref like this:
// Create a reference under which you want to list
var listRef = storage.ref().child(`${doc.data().roomPhotoId}/`);
// Find all the prefixes and items.
listRef.listAll()
.then((res) => {
res.prefixes.forEach((folderRef) => {
// All the prefixes under listRef.
// You may call listAll() recursively on them.
});
res.items.forEach((itemRef) => {
// All the items under listRef.
});
}).catch((error) => {
// Uh-oh, an error occurred!
});
Make sure to use listAll.
Be aware that:
root.child('images').listAll() will return /images/uid as a prefix.
root.child('images/uid').listAll() will return the file as an item.
You can find more about it here.
Your code with grouping the downloadURLS:
useEffect(() => {
setLoading(true);
Promise.all([getRooms(), getLocation()])
.then((values) => {
const roomsSnapshot = values[0];
const rooms = [];
const pUrl = [];
roomsSnapshot.forEach((doc) => {
const splitAddress = doc.data().address.split(", ");
formatedAddress.current = splitAddress[1] + " " + splitAddress[0];
//Download from storage//
rooms[`${doc.data().roomPhotoId}`]=[]
storage
.ref(`${doc.data().roomPhotoId}/`)
.list()
.then(function (result) {
result.items.forEach((imageRef) => {
imageRef.getDownloadURL().then((url) => {
console.log(url)
roomItems.push(url)
});
});
setRoomsImagesCounter(roomsImagesCounter + 1);
// no photos scenario
if (result.items.length === 0) {
setLoading(false);
}
});
//pushing entity data//
rooms[`${doc.data().roomPhotoId}`].push({
...doc.data(),
id: doc.id,
photosURL: roomItems,
shortAddress: formatedAddress.current,
coordsAddress: coords.current,
});
});
console.log(rooms);
setRooms(rooms);
// getPhotos(rooms);
setLoading(false);
})
.catch((err) => {
console.log("Error getting getting rooms or user role", err);
});
// eslint-disable-next-line react-hooks/exhaustive-deps }, []);

Array.map() doesn't render anything in React

I'm trying to make a list in my react app. I have retrieved data from my database, and pushed it into a list. I have doublechecked that the data shows up correctly in the console, and it does, but array.map() returns nothing. I think the problem might be that array.map() runs two times. I don't know why it runs two times.
function Dashboard() {
const user = firebase.auth().currentUser;
const [teams, setTeams] = useState([])
const history = useHistory();
useEffect(() => {
getTeams()
if (user) {
} else {
history.push("/")
}
}, [])
function Welcome() {
if (user) {
return <h1>Welcome, {user.displayName}</h1>
} else {
}
}
const getTeams = () => {
firebase.firestore().collectionGroup('members').where('user', '==', user.uid).get().then((snapshot) => {
const docList = []
snapshot.forEach((doc) => {
docList.push({
teamId: doc.data().teamId,
})
})
const teamslist = []
docList.forEach((data) => {
firebase.firestore().collection('teams').doc(data.teamId).get().then((doc) => {
teamslist.push({
name: doc.data().name,
teamId: doc.id,
})
})
})
setTeams(teamslist)
})
}
const openTeam = (data) => {
console.log(data.teamId)
}
return (
<div>
<Welcome />
<div>
<ul>
{console.log(teams)}
{teams.map((data) => {
return (
<li onClick={() => openTeam(data)} key={data.teamId}>
<h1>{data.name}</h1>
<p>{data.teamId}</p>
</li>
)
})}
</ul>
</div>
</div>
)
}
export default Dashboard
The getTeams function has a bug where it isn't waiting for the firebase.firestore().collection('teams').doc(data.teamId).get().then promises to finish before calling setTeams, so it is called with an empty array, causing React to trigger a render with the empty array.
As the promises for fetching each team resolve they will be pushed to the same array reference, but this won't trigger a rerender in React since you're not calling setTeams again when the array changes.
Try this code, which won't call setTeams until each team promise generated from docList has been resolved.
const getTeams = () => {
firebase.firestore().collectionGroup('members').where('user', '==', user.uid).get().then((snapshot) => {
const docList = []
snapshot.forEach((doc) => {
docList.push({
teamId: doc.data().teamId,
})
})
const teamslist = [];
Promise.all(docList.map((data) => {
return firebase
.firestore()
.collection('teams')
.doc(data.teamId)
.get()
.then((doc) => {
teamslist.push({
name: doc.data().name,
teamId: doc.id,
})
})
}))
.then(() => setTeams(teamslist));
})
}
A smaller edit would be to call setTeams after each separate team promise resolves, which will trigger a React render each time a new team is resolved:
.then((doc) => {
teamslist.push({
name: doc.data().name,
teamId: doc.id,
});
// create a new array, since using the same array
// reference won't cause react to rerender
setTeams([...teamslist]);
})
Many thanks to #martinstark who provided you an answer while I was unavailable.
However, there are some more things that need to be covered.
User State
In your current component, you pull the current user from Firebase Authentication, but don't handle the state changes of that user - signing in, signing out, switching user. If a user is signed in and they were to navigate directly to your dashboard, firebase.auth().currentUser could be momentarily null while it resolves the user's login state, which would incorrectly send them off to your login page.
This can be added using:
const [user, setUser] = useState(() => firebase.auth().currentUser || undefined);
const userLoading = user === undefined;
useEffect(() => firebase.auth().onAuthStateChanged(setUser), []);
Next, in your first useEffect call, you call getTeams() whether the user is signed in or not - but it should depend on the current user.
useEffect(() => {
if (userLoading) {
return; // do nothing (yet)
} else if (user === null) {
history.push("/");
return;
}
getTeams()
.catch(setError);
}, [user]);
// This getTeams() is a () => Promise<void>
const getTeams = async () => {
const membersQuerySnapshot = await firebase.firestore()
.collectionGroup('members')
.where('user', '==', user.uid)
.get();
const docList = []
membersQuerySnapshot.forEach((doc) => {
docList.push({
teamId: doc.get("teamId"), // better perfomance than `doc.data().teamId`
});
});
const teamDataList = [];
await Promise.all(docList.map((data) => {
return firebase.firestore()
.collection('teams')
.doc(data.teamId)
.get()
.then(doc => teamDataList.push({
name: doc.get("name"),
teamId: doc.id
}));
}));
setTeams(teamDataList);
}
Optimizing getTeams() - Network Calls
The getTeams function in your question calls setTeams with the array [], which will be empty at the time of calling it as covered in #martinstark's answer. The "get team data" operations are asyncronous and you aren't waiting for them to resolve before updating your state and triggering a new render. While you are pushing data to them after the component has rendered, modifying the array won't trigger a new render.
While you could fetch the data for each team using db.collection("teams").doc(teamId).get(), each of these is requests is a network call, and you can only make a limited number of these in parallel. So instead of fetching 1 team per network call, you could fetch up to 10 teams per network call instead using the in operator and FieldPath.documentId().
Assuming the collectionGroup("members") targets the collections of documents at /teams/{aTeamId}/members which contain (at least):
"/teams/{aTeamId}/members/{memberUserId}": {
teamId: aTeamId,
user: memberUserId, // if storing an ID here, call it "uid" or "userId" instead
/* ... */
}
// this utility function lives outside of your component near the top/bottom of the file
function chunkArr(arr, n) {
if (n <= 0) throw new Error("n must be greater than 0");
return Array
.from({length: Math.ceil(arr.length/n)})
.map((_, i) => arr.slice(n*i, n*(i+1)))
}
// This getTeams() is a () => Promise<void>
const getTeams = async () => {
const membersQuerySnapshot = await firebase.firestore()
.collectionGroup('members')
.where('user', '==', user.uid)
.get();
const teamIDList = []
membersQuerySnapshot.forEach((doc) => {
teamIDList.push(doc.get("teamId")); // better perfomance than `doc.data().teamId`
})
const chunkedTeamIDList = chunkArr(teamIDList, 10) // split into batches of 10
const teamsColRef = firebase.firestore().collection('teams');
const documentId = firebase.firestore.FieldPath.documentId(); // used with where() to target the document's ID
const foundTeamDocList = await Promise
.all(chunkedTeamIDList.map((chunkOfTeamIDs) => {
// fetch each batch of IDs
return teamsColRef
.where(documentId, 'in', chunkOfTeamIDs)
.get();
}))
.then((arrayOfQuerySnapshots) => {
// flatten results into a single array
const allDocsList = [];
arrayOfQuerySnapshots.forEach(qs => allDocsList.push(...qs.docs));
return allDocsList;
});
const teamDataList = foundTeamDocList
.map((doc) => ({ name: doc.get("name"), teamId: doc.id }));
// sort by name, then by ID
teamDataList.sort((aTeam, bTeam) =>
aTeam.name.localeCompare(bTeam.name) || aTeam.teamId.localeCompare(bTeam.teamId)
)
// update state & trigger render
setTeams(teamDataList);
}
You can also make use of this utility function to simplify & optimize the code a bit. Which gives:
// This getTeams() is a () => Promise<void>
const getTeams = async () => {
const membersQuerySnapshot = await firebase.firestore()
.collectionGroup('members')
.where('user', '==', user.uid)
.get();
const teamIDList = []
membersQuerySnapshot.forEach((doc) => {
teamIDList.push(doc.get("teamId")); // better perfomance than `doc.data().teamId`
})
const teamsColRef = firebase.firestore().collection('teams');
const teamDataList = [];
await fetchDocumentsWithId(
teamsColRef,
teamIDList,
(doc) => teamDataList.push({ name: doc.get("name"), teamId: doc.id })
);
// sort by name, then by ID
teamDataList.sort((aTeam, bTeam) =>
aTeam.name.localeCompare(bTeam.name) || aTeam.teamId.localeCompare(bTeam.teamId)
)
// update state & trigger render
setTeams(teamDataList);
}
Optimizing getTeams() - Function Definition
As part of the last optimization, you could pull it out of your component or place it in its own file so that it's not redefined with every render:
// define at top/bottom of the file outside your component
// This getTeams() is a (userId: string) => Promise<{ name: string, teamId: string}[]>
async function getTeams(userId) => {
const membersQuerySnapshot = await firebase.firestore()
.collectionGroup('members')
.where('user', '==', userId)
.get();
const teamIDList = []
membersQuerySnapshot.forEach((doc) => {
teamIDList.push(doc.get("teamId")); // better perfomance than `doc.data().teamId`
})
const teamsColRef = firebase.firestore().collection('teams');
const teamDataList = [];
await fetchDocumentsWithId(
teamsColRef,
teamIDList,
(doc) => teamDataList.push({ name: doc.get("name"), teamId: doc.id })
);
// sort by name, then by ID
teamDataList.sort((aTeam, bTeam) =>
aTeam.name.localeCompare(bTeam.name) || aTeam.teamId.localeCompare(bTeam.teamId)
)
// return the sorted teams
return teamDataList
}
and update how you use it:
useEffect(() => {
if (userLoading) {
return; // do nothing
} else if (user === null) {
history.push("/");
return;
}
getTeams(user.uid)
.then(setTeams)
.catch(setError);
}, [user]);

Firebase unsubscribe to onSnapshot is not working

So I'm trying to load multiple elements (RoomItem) and each RoomItem has an onSnapshot listener that listens to real-time changes. Now when I change my Workspace which loads a new set of RoomItems, the previous listeners don't unsubscribe and if there's any update in that RoomItem then react renders that list and not the one which should've been there coming from currentWorkspace.
const [roomLiveStatus, setRoomLiveStatus] = useState(false);
const [unsubscribe, setUnsubscribe] = useState(null);
const getRoomData = (currentWorkspace) => {
const {
roomData,
workspace,
allChannels,
setChannels,
index,
currentUser,
} = props;
const { workspaceId } = workspace;
const workspaceIdLowerCase = workspaceId.toLowerCase();
const { roomId } = roomData;
const roomIdLowerCase = roomId.toLowerCase();
const now = new Date().valueOf();
const query = firebase
.firestore()
.collection(`workspaces/${currentWorkspace.workspaceId}/rooms/${roomId}/messages`);
let unsub;
unsub = query.onSnapshot(
{
includeMetadataChanges: true,
},
function (doc) {
doc.docChanges().forEach((change) => {
if (change.type === "added") {
if (change.doc.data().timestamp >= now) {
console.log("message added ", change.doc.data());
let prevAllChannels = allChannels;
firebase
.firestore()
.collection(`workspaces/${currentWorkspace.workspaceId}/rooms/`)
.doc(`${roomId}`)
.get()
.then((doc) => {
if (doc.exists) {
console.log("updated room data", {
...doc.data(),
roomId: doc.id,
});
prevAllChannels.splice(index, 1, {
...doc.data(),
roomId: doc.id,
lastMessage: change.doc.data(),
});
if(currentWorkspace?.workspaceId === workspaceId) {
switchSort(prevAllChannels);
}
}
});
}
}
if (change.type === "modified") {
console.log("message modified: ", change.doc.data());
let prevAllChannels = allChannels;
firebase
.firestore()
.collection(`workspaces/${workspaceId}/rooms/`)
.doc(`${roomId}`)
.get()
.then((doc) => {
if (doc.exists) {
prevAllChannels.splice(index, 1, {
...doc.data(),
roomId: doc.id,
});
// console.log(prevAllChannels,"prevallchannels",prevSortType,"prevsorttype", props.sortType,"currentsorttype")
if(currentWorkspace?.workspaceId === workspaceId) {
switchSort(prevAllChannels, props.sortType);
}
}
});
}
if (change.type === "removed") {
console.log("message removed: ", change.doc.data());
}
});
}
);
setUnsubscribe(() => unsub);
}
useEffect(() => {
getRoomData(props.currentWorkspace);
}, []);
useEffect(() => {
getRoomData(props.currentWorkspace);
}, [props.sortType, props.currentWorkspace]);
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
const prevCurrentWorkspace = usePrevious(props.currentWorkspace)
useEffect(() => {
if(unsubscribe) {
unsubscribe();
setUnsubscribe(null);
}
},[props.workspace, props.currentWorkspace])
useEffect(() => {
return(() => {
if(unsubscribe)
unsubscribe()
setUnsubscribe(null);
})
},[])

Categories

Resources