Skip to content

Instantly share code, notes, and snippets.

@keith-kurak
Last active January 12, 2022 04:10
Show Gist options
  • Save keith-kurak/02e60959bbf3e9e9bbb019307cfbf9ab to your computer and use it in GitHub Desktop.
Save keith-kurak/02e60959bbf3e9e9bbb019307cfbf9ab to your computer and use it in GitHub Desktop.
03: Hello, Firebase!
// add Firebase as backend, loading and saving channels
// add actions to start and stop streaming channels, saving them to a channels array
// change Channel.id type to "string" (or "identifier") because that's what firebase wants!
// ...
id: types.string,
// ...
let unsubscribeFromChannelsFeed; // we could later use this to tear down on logout... or something
const startStreamingChannels = () => {
const db = getFirestore();
const q = query(collection(db, "channels"));
unsubscribeFromChannelsFeed = onSnapshot(q, (querySnapshot) => {
self.updateChannels(querySnapshot);
});
};
const stopStreamingChannels = () => {
unsubscribeFromChannelsFeed();
}
// semi-private function only used to encapsulate channel update
const updateChannels = (querySnapshot) => {
self.channels = [];
querySnapshot.forEach((doc) => {
self.channels.push({ id: doc.id, name: doc.data().name });
});
};
// make sure to return them at the end of the actions callback!
// start streaming channels from Firebase when ChannelsScreen is mounted
useEffect(() => {
rootStore.startStreamingChannels();
return rootStore.stopStreamingChannels; // this causes the stop streaming to be called on unmount
}, []);
// update addChannel to add the channel to firebase. Due to streaming, it will automatically show up in the channels array
const addChannel = flow(function* addChannel() {
const db = getFirestore();
// add new document with auto-id
yield addDoc(collection(db, "channels"), {
name: uniqueNamesGenerator({
dictionaries: [adjectives, animals],
length: 2,
separator: "-",
}),
});
});
// BONUS: update the name of the ChatScreen based on the channel name
<Stack.Screen
name="Chat"
component={ChatScreen}
options={({ route }) => {
const channel = rootStore.channelsSorted.find(
(c) => c.id === route.params.channelId
);
return { title: channel ? channel.name : "Chat" };
}}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment