Blog>
Snippets

Using TanStack Config for State Management with Firebase

Provides an example of using TanStack Config to manage the application state, focusing on integrating real-time updates from Firebase for efficient rendering.
import { createTanStackStore } from '@tanstack/solid-store';
import firebase from 'firebase/app';
import 'firebase/firestore';

// Initialize Firebase
// Note: Replace the below config with your Firebase project configuration
const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
  storageBucket: 'YOUR_STORAGE_BUCKET',
  messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
  appId: 'YOUR_APP_ID'
};

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
This piece of code initializes Firebase with your project's configuration and sets up Firestore for database interactions.
const store = createTanStackStore({
  initialState: { messages: [] }
});
Creates a new instance of TanStack Store with the initial state set to an empty array of messages.
function fetchMessages() {
  return db.collection('messages').get().then(snapshot => {
    const messages = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
    store.setState({ messages });
  });
}
Defines a function to fetch messages from the 'messages' collection in Firestore and update the store's state with these messages.
function subscribeToMessageUpdates() {
  db.collection('messages').onSnapshot(snapshot => {
    const messages = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
    store.setState({ messages });
  });
}
Sets up a real-time listener on the 'messages' collection in Firestore. Whenever there are changes, it updates the store's state with the new set of messages.
subscribeToMessageUpdates();
Calls the function to start listening for real-time updates from Firestore.