Home > Software engineering >  Firebase RTDB .update function not working?
Firebase RTDB .update function not working?

Time:09-03

I'm trying to update a node in a post reference in my Firebase Realtime Database, but for some reason it's not working. The console logs the full path, not too sure what I'm doing wrong. I've tried different variations of function creation, but none seem to be working. Any help here is greatly appreciated, thank you! Still relatively new to react.

Code:

import React, { useEffect, useContext } from "react";
import ReactDOM from "react-dom";
import { CSSTransition } from "react-transition-group";
import { useParams, useNavigate } from 'react-router-dom';
import { DatabaseContext } from '../contexts/database-context';
import Gallery from 'react-grid-gallery';
import '../scss/pages/HomeDetailPage.scss'
import { getAuth } from "firebase/auth";

import { getDatabase, onValue, ref, set, push, Database, DataSnapshot } from "firebase/database";
import "../scss/components/Modal.scss";



const Modal = props => {

  //https://codesandbox.io/s/magical-christian-qxtdm?from-embed=&file=/src/App.js:111-151

  const auth = getAuth();
  const cUser = auth.currentUser;

  const navigate = useNavigate();

  const navigateTo = (path) => {
    navigate(path)
  }

  const { GetSelectedListingDetail, GetListingOwner, selectedListing, listingOwner } = useContext(DatabaseContext);
  const {
    address,
    bathrooms,
    bedrooms,
    creationDate,
    description,
    images,
    postKey,
    latitude,
    longitude,
    postRef,
    postUrl,
    poster,
    price,
    rawPrice,
    squareFeet,
    view_Count,
    isHighlighted
  } = selectedListing || '';

  const { email } = listingOwner || '';
  const params = useParams();

  const closeOnEscapeKeyDown = e => {
    if ((e.charCode || e.keyCode) === 27) {
      props.onClose();
    }
  };

  useEffect(() => {
    document.body.addEventListener("keydown", closeOnEscapeKeyDown);
    return function cleanup() {
      document.body.removeEventListener("keydown", closeOnEscapeKeyDown);
    };
  }, []);

  function writeUserData() {
    const db = getDatabase();
    const key = props.postKey;
    
    const listingRef = db.ref('listings/'   key);
    console.log(listingRef);
    listingRef.update({
      price: 'SOLD'
    });
  }

  return ReactDOM.createPortal(
    <CSSTransition
      in={props.show}
      unmountOnExit
      timeout={{ enter: 0, exit: 300 }}
    >
      <div className="modal" onClick={props.onClose}>
        <div className="modal-content" onClick={e => e.stopPropagation()}>
          <div className="home-detail-page-col-1">
            <Gallery
              images={Object.values(props.images).map((url) => ({
                src: url,
                thumbnail: url,
                alt: 'alt txt'
              }))}
              enableImageSelection={false}
            />

          </div>

          <div className="home-detail-page-col-2">
            <div className="detailDiv">

              <div className='actionDiv'>
                <button className='closeBtn' onClick={props.onClose}> </button>
              </div>

              <div className="propInfo">
                <p className="title is-2 mb-5">{props.price}</p>
                <p className="subtitle is-6 mb-2">{props.address}</p>
                <p className="subtitle is-6">{props.bedrooms   ' | '   props.bathrooms   ' | '   props.squareFeet}</p>

              </div>
              {
                (cUser && cUser.uid !== props.poster) &&
                <div className="contactBtn">
                  <button className="contactButton" href={`mailto:${props.email}`}>Contact Owner</button>
                </div>
              }
              {
                (cUser && cUser.uid === props.poster) &&
                <div className="contactBtn">
                  <button className="contactButton" onClick={() => writeUserData()}>Mark as Sold</button>
                </div>
              }
              {
                !cUser &&
                <div className="contactBtn">
                  <button className="contactButton" onClick={() => navigateTo('/signin')}>Sign in to contact</button>
                </div>
              }


              <div className="propDesc">
                <p className="title is-5">Property Overview:</p>

                <p className="title is-6 pb-4">
                  {props.description}
                </p>
              </div>


            </div>
          </div>
        </div>
      </div>
    </CSSTransition>,
    document.getElementById("root")
  );
};

export default Modal;

CodePudding user response:

You are using the Firebase Modular SDK that has a functional syntax and update() is a function that can be imported from the Realtime Database SDK as shown below:

import { ref, update, getDatabase } from "firebase/database"

function writeUserData() {
  const db = getDatabase();
  const key = props.postKey;

  const listingRef = ref(db, 'listings/'   key); // and not db.ref(...)

  update(listingRef, {
    price: 'SOLD'
  }).then(() => {
    console.log("Data updated")
  }).catch((e) => console.log(e))
}
  • Related