I am attempting to link my Firebase real-time database with Cloud Firestore, but I am encountering import errors in the process

I am currently working on enhancing the online functionality of my chat app by implementing a presence system using Firebase Realtime Database. Here is the code snippet that I have created for this purpose:

db refers to Firestore and dbt refers to the Realtime Database

import { auth, db, dbt } from "@/firebase/firebase";
import { ref as rtdbRef, set, onValue, onDisconnect } from "firebase/database";
const connectedRef = rtdbRef(dbt, ".info/connected");
const myConnectionsRef = rtdbRef(dbt, `status/` + user.uid);
onValue(connectedRef, (snap) => {
  if (snap.val() === false) {
  return ;
}
onDisconnect(myConnectionsRef).set("disconnected").then(() => {
  updateFirestoreUser(true, user);
  set(myConnectionsRef, "connected")
});

In order to achieve my goal of updating the 'isOnline' variable in Firestore cloud when a user goes offline, I came across a solution from the Firebase documentation. However, I encountered errors with each line of the provided code:

var userStatusFirestoreRef = firebase.firestore().doc('/status/' + uid);
var isOfflineForFirestore = {
  state: 'offline',
  last_changed: firebase.firestore.FieldValue.serverTimestamp(),
};
var isOnlineForFirestore = {
  state: 'online',
  last_changed: firebase.firestore.FieldValue.serverTimestamp(),
};
firebase.database().ref('.info/connected').on('value', function(snapshot) {
  if (snapshot.val() == false) {
      userStatusFirestoreRef.set(isOfflineForFirestore);
      return;
  };
  userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function() {
    userStatusDatabaseRef.set(isOnlineForDatabase);
    userStatusFirestoreRef.set(isOnlineForFirestore);
  })
});

Answer №1

Here is a code snippet that demonstrates how to update a value in Firestore cloud using the real-time database presence system. While it may not be an exact solution to your query, it serves as a suitable workaround.

useEffect(() => {
    const userStatusRef = rtdbRef(dbt, `status/` + currentUser?.uid);
    onValue(userStatusRef, (snapshot) => {
        const data = snapshot.val();
        console.log(data);
        if(data === "connected"){
            updateFirestoreUser(true, currentUser);
        }else{
            updateFirestoreUser(false, currentUser);
        }
    });
    //eslint-disable-next-line
}, [])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problems with Ajax functionality in CodePen

Currently working on the Wikipedia Viewer project for freeCodeCamp. I'm encountering an issue with the ajax function as nothing is being logged in the console upon click. The code snippet in question is provided below. Appreciate any help or insight o ...

RobotFramework encounters difficulty locating an element using JavaScript

After working with RF for the past few weeks, I came across a persistent issue that has been bothering me. I keep getting the following error: The element with the locator 'XXX' (just a template) cannot be found. Upon investigating the span tha ...

Acquire user input using AngularJS

Is it possible to retrieve the value of an input text using AngularJS without utilizing a Controller? If so, what approach would achieve this? I have come across some resources discussing similar queries, but they all involve .controller here is one such ...

Tips on getting the bot to react to a single "event" mentioned in the sentence, without multiple occurrences

Things are a bit complicated, but here's an example to illustrate: I've set up this event: client.on('message', async message => { if (message.content.toLowerCase().includes("megumin")) { message.channel.send("W ...

Getting the Correct Nested Type in TypeScript Conditional Types for Iterables

In my quest to create a type called GoodNestedIterableType, I aim to transform something from Iterable<Iterable<A>> to just A. To illustrate, let's consider the following code snippet: const arr = [ [1, 2, 3], [4, 5, 6], ] type GoodN ...

Using fancybox to send an ajax post request to an iframe

Can you send a variable to the iframe when using fancybox? This is my current setup: function fancyBoxLoad(element) { var elementToEdit = $("#" + $(element).attr("class")); var content = encodeURIComponent($(elementToEdit).oute ...

Storing a portion of AJAX response as a PHP variable

Is there a way to store data received through an AJAX response in a PHP variable? I want to take the value of $('#attempts_taken').val(data[11]); and save it as a PHP variable. Any help would be great! <script type="text/javascript> $(do ...

Guide to selecting an element with a combination of text and a random number using Selenium with JavaScript

<a id="Message4217" class="btn-sm btn-danger Message" data-id="4217"><span class="icon-adjustment icon-trash"></span> Delete</a> The objective is to remove a message base ...

Apply a specific CSS class to a division depending on the currently active cookie

I have implemented cookies on specific pages using https://github.com/carhartl/jquery-cookie. Could someone guide me on how to apply a CSS class to an ID (e.g., adding class .red to #mouse if the cookie named "socks" is active)? For example: If there is ...

NodeJS refuses to import a file that is not compatible with its structure

My website has two important files: firebase.js gridsome-server.js The firebase.js file contains JavaScript code related to Firebase integration: import firebase from 'firebase/app' import 'firebase/firestore' const config = { ap ...

Navigating through child elements within a div using JavaScript

I recently coded a div using this snippet... let sidebarBox = document.createElement("div"); sidebarBox.id = "sidebarBox"; ...and then I created a second div like so... let sidebarAd = document.createElement("div"); sidebarAd.className = "sidebarAd"; B ...

Experiencing Issues with File Downloading on Express Server with Axios and Js-File-Download Library

I developed a feature on my express server that allows users to download a file easily. app.post("/download", (req, res) => { let file_name = req.body.name; res.download(path.join(__dirname, `files/${file_name}.mp3`), (err) => { ...

What could be causing the TypeError that is preventing my code from running smoothly?

I can't seem to figure out why I'm constantly encountering the error message Cannot destructure property 'id' of 'this.props.customer' as it is undefined.. Despite double-checking my code and making sure everything looks corre ...

`Formatting Dates with Google Script`

I am looking to modify the date format from "mmm-dd-yyyy" (Nov-11-2019) using my existing code. Here is the code snippet: var timeStamp = data[i][timeStampappr]; var formatted = (timeStamp.getMonth()+1) + '/' + timeStamp.getDate() + &ap ...

Omitting a specific element from the design of the current child route in Next.js 13

How can I modify the root layout in Nextjs 13 using the app router to exclude a specific element from being rendered in a child route? Specifically, I want to remove the aside with the Feed component while keeping the rest of the code intact: // Exclude ...

Ways to attach an item using its lower point instead of its upper coordinate

I am currently working on a poker table project using React. As of now, I have player components that need to be strategically positioned around the table. One challenge I'm facing is that when the screen attribute changes, the position of the top tw ...

Analyzing objects within an array for similarities

Suppose I have an array containing objects: var arr = [ { id: 1, pt: 0 }, { id: 2, pt: 12 }, { id: 3, pt: 7 }, { id: 4, pt: 45 }, { id: 5, pt: 123 }, ]; I am looking to loop through this array (possibly using array.forEach or array.map) ...

Displaying a Countdown in a Django Loop: A Step-by-Step

Hey there, I've got a Javascript countdown nested in a Django for loop that's causing some trouble by displaying multiple instances. Currently, only the first countdown works when I click on any of the start buttons. I'd like each button to ...

What are some creative ways to represent data using different numerical intervals?

Looking to develop a visualization of a .CSV file containing 1.2 million lines, showcasing addresses in the format: source , destination 12.251.512 , 12.623.743 51.734.312 , 23.233.991 6334.6231.123 , 42.532.54453 (utiliz ...

Error: Unable to modify the value of a protected property '0' in the object 'Array'

I am facing a challenging issue with implementing a Material UI slider in conjunction with Redux. Below is the code for the slider component: import { Slider } from '@material-ui/core' const RangeSlider = ({handleRange, range}) => { ...