Blog>
Snippets

Implementing a Real-time Chat Feature

Illustrates the complete integration process by building a simple real-time chat feature using Firebase for back-end data management and TanStack Config for state management.
import { createTanStackStore } from '@tanstack/solid-store';
import firebase from 'firebase/app';
import 'firebase/firestore';

// Firebase config initialization
firebase.initializeApp({/* Firebase config object */});
const firestore = firebase.firestore();
This piece of code initializes Firebase with the provided configuration and sets up Firestore for database operations. It also imports TanStack Store for state management.
const store = createTanStackStore({
 initialState: { messages: [] },
});
Here, a TanStack store is created with an initial state. The state includes a 'messages' array to hold the chat messages.
const messagesCollectionRef = firestore.collection('messages');

store.subscribe(async () => {
 const snapshot = await messagesCollectionRef.orderBy('timestamp').get();
 const messages = snapshot.docs.map(doc => doc.data());
 store.setState({ messages });
});
This snippet sets up a subscription to Firestore's 'messages' collection. Whenever there's a change in the Firestore collection, it updates the 'messages' state in the TanStack Store.
const sendMessage = async (message) => {
 await messagesCollectionRef.add({
   text: message,
   timestamp: firebase.firestore.FieldValue.serverTimestamp(),
 });
};
Defines a function to send a message. It adds a new document to the 'messages' collection in Firestore with the message text and a server timestamp.
store.subscribe(state => {
 console.log(state.messages);
});
Subscribes to the store's state changes to log out the latest messages. This can be used for displaying messages in the UI.