Skip to content

Instantly share code, notes, and snippets.

@vishalnarkhede
Last active April 14, 2020 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishalnarkhede/7a18641dd5cc94e7e0c4083293d39b39 to your computer and use it in GitHub Desktop.
Save vishalnarkhede/7a18641dd5cc94e7e0c4083293d39b39 to your computer and use it in GitHub Desktop.
import React, {useState, useEffect} from 'react';
const useWatchedChannels = (client, changeChannel) => {
const [activeChannelId, setActiveChannelId] = useState(null);
const [unreadChannels, setUnreadChannels] = useState([]);
const [readChannels, setReadChannels] = useState([]);
const [oneOnOneConversations, setOneOnOneConversations] = useState([]);
const [hasMoreChannels, setHasMoreChannels] = useState(true);
const filters = {
type: 'messaging',
example: 'slack-demo',
members: {
$in: [client.user.id],
},
};
const sort = {has_unread: -1, cid: -1};
const options = {limit: 30, state: true};
useEffect(() => {
if (!hasMoreChannels) {
return;
}
let offset = 0;
const _unreadChannels = [];
const _readChannels = [];
const _oneOnOneConversations = [];
/**
* fetchChannels simply gets the channels from queryChannels endpoint
* and sorts them by following 3 categories:
*
* - Unread channels
* - Channels (read channels)
* - Direct conversations/messages
*/
async function fetchChannels() {
const channels = await client.queryChannels(filters, sort, {
...options,
offset,
});
offset = offset + channels.length;
channels.forEach(c => {
if (c.countUnread() > 0) {
_unreadChannels.push(c);
} else if (Object.keys(c.state.members).length === 2) {
_oneOnOneConversations.push(c);
} else {
_readChannels.push(c);
}
});
setUnreadChannels([..._unreadChannels]);
setReadChannels([..._readChannels]);
setOneOnOneConversations([..._oneOnOneConversations]);
if (channels.length === options.limit) {
fetchChannels();
} else {
setHasMoreChannels(false);
setActiveChannelId(_readChannels[0].id);
changeChannel(_readChannels[0].id);
}
}
fetchChannels();
}, [client]);
return {
activeChannelId,
setActiveChannelId,
unreadChannels,
setUnreadChannels,
readChannels,
setReadChannels,
oneOnOneConversations,
setOneOnOneConversations,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment