Blog>
Snippets

Integrating TanStack Store with Cloud Services

Showcase a real-world example of integrating TanStack Store with a cloud service (e.g., Firebase) for real-time data synchronization across clients.
import { createTanStackStore } from '@tanstack/solid-store';
import { ref } from '@tanstack/react-query';
import firebase from 'firebase/app';
import 'firebase/firestore';
This code imports the necessary modules to set up a TanStack store with Firebase as the cloud service. It includes the TanStack store creator, React Query for managing async queries, and the Firebase libraries.
const store = createTanStackStore({
  initialState: { messages: [] },
});
Initializes the TanStack store with an initial state. Here, `messages` is used as an example state that will hold chat messages synchronized with Firebase.
firebase.initializeApp({/* Firebase config object */});
const firestore = firebase.firestore();
Initializes Firebase with your project's configuration (obtained from your Firebase console) and creates a Firestore instance to interact with your database.
const messagesCollectionRef = firestore.collection('messages');

function subscribeToMessages() {
  return messagesCollectionRef
    .orderBy('timestamp')
    .onSnapshot(snapshot => {
      const messages = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
      store.setState({ messages });
    },
    error => console.error(error));
}
Defines a function to subscribe to the 'messages' collection in Firestore. The function listens for real-time updates, orders messages by timestamp, and updates the TanStack store's state with the new messages.
function sendMessage(message) {
  return messagesCollectionRef.add({
    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 and a server timestamp.
subscribeToMessages();
Calls the `subscribeToMessages` function to start listening to real-time updates from the Firestore 'messages' collection. This ensures the TanStack store is always in sync with the cloud data.