I'm having trouble figuring out why my Vue method isn't successfully deleting a Firebase object. Can anyone offer some guidance

What I am trying to achieve:

I have been struggling to use the remove method from Firebase. I have read the documentation, but for some reason, it is not working as expected. Retrieving data using snapshot works fine, but when I try to delete using the remove method, nothing happens. Initially, I was getting an error on the reference until I used _key in the onClick button.

Although it logs some data to the console, it fails to delete the gigs/user/key object. Any thoughts on why this might be happening?

<template>
  <v-container id="tutorials">
      <h1>Gigs Available!</h1>
           <!-- loop over the tutorials -->
           <div  class="Agrid d-grid">
           <div
           class="Amodule  back"
           v-for="gig in allGigs"
           :key="gig._key">
           <div class="fill-height">
             <v-container >
              <a @click.prevent="deleteGigs(gig._key)" class="card-link">
                 <v-icon color=red>mdi-delete</v-icon>
               </a>
             <br>
             <div class="d-flex align-start">
               <h3 class="j-title center mb-00">{{ gig.gigtitle}}</h3>
             </div>
             <h6 class="">{{gig.companyname}}</h6>
             <v-row class="d-flex ">
               <p class="col-tres mdi mdi-clock text--secondary"> {{ gig.vacanttype }} </p>
               <p class="col-tres mdi mdi-earth text--secondary"> {{ gig.giglocation }} </p>
               <p class="col-tres mdi mdi-calendar text--secondary">{{gig.gigdate}} </p>
             </v-row>
             <v-divider class="mx-4"></v-divider>
             <h5 class="left text-body-2">Company description</h5><br>
             <p class="content"> {{ gig.companydescription}}</p><br>
             <h5 class="left text-body-2">Gig description</h5><br>
             <p class="content"> {{ gig.gigdescription}}</p><br>
             <h5 class="left text-body-2">Gig benefits</h5><br>
             <p class="content"> {{ gig.gigbenefits}}</p><br>
             <h5 class="left text-body-2">Skills</h5><br>
             <p class="content"> {{ gig.gigskills}}</p><br>
           </v-container>
         </div>
     </div>
   </div>
     <br>

  </v-container>
</template>
<script>
import firebase from '@/plugins/firebase'
let db = firebase.database();
//let usersRef = db.ref('users');
let gigRef = db.ref('gigs');

export default {
  name: 'EditGigs',
  data: () => ({
  authUser: null,
  allGigs: [], // initialise an array
}),
  methods: {
    deleteGigs(gig) {
    gigRef.child(gig).remove()
    console.log(gigRef.child(gig))
}
  },
  created: function() {
    //data => console.log(data.user, data.credential.accessToken)
    firebase.auth().onAuthStateChanged(user => {
        if (user) {
          gigRef.once('value', snapshot => {
            const val = snapshot.val()
            if (val) {
              this.allGigs = Object.values(val).flatMap(gigs =>
              Object.entries(gigs).map(([ _key, gig ]) => ({ _key, ...gig})))
            }
            console.log(snapshot.val())
          });
        }
     })
}
}

After clicking the delete button, I see this :

Reference {repo: Repo, path: Path, queryParams_: QueryParams, orderByCalled_: false}
orderByCalled_: false
path: Path {pieces_: Array(2), pieceNum_: 0}
queryParams_: QueryParams {limitSet_: false, startSet_: false, startNameSet_: false, endSet_: false, endNameSet_: false, …}
repo: Repo {repoInfo_: RepoInfo, app: FirebaseAppImpl, dataUpdateCount: 1, statsListener_: null, eventQueue_: EventQueue, …}
database: Database
key: "-MjxHR5FjvNgB_cvp5Q3"
parent: Reference
orderByCalled_: false
path: Path {pieces_: Array(1), pieceNum_: 0}
queryParams_: QueryParams {limitSet_: false, startSet_: false, startNameSet_: false, endSet_: false, endNameSet_: false, …}
repo: Repo {repoInfo_: RepoInfo, app: FirebaseAppImpl, dataUpdateCount: 1, statsListener_: null, eventQueue_: EventQueue, …}
database: Database
key: "gigs"
parent: Reference
ref: Reference

UI thing

If I do this, it removes all the ref objects...

  methods: {
  deleteGigs(gig) {
    gigRef.remove()
    //console.log(gigRef.child(gig))
    console.log(gig)
   }
  },

Answer №1

After some digging, I've discovered the solution:

The Firebase snapshot key is structured in a specific way: firebase key website

Retrieving the key from any DataSnapshot will provide the key for the corresponding location. However, trying to retrieve the key from the root URL of a Database will result in null.

This means we need to associate it with a key inside the object, making the firebase real-time DB vulnerable

Take a look at this illustration highlighting the flaw in design:

real time design of key hierarchy

Has anyone encountered a similar issue with mongo DB?

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

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...

How can we combine refs in React to work together?

Let's consider this scenario: I need a user to pass a ref to a component, but I also have to access that same ref internally. import React, { useRef, forwardRef } from 'react'; import useId from 'hooks/useId'; interface Props ext ...

Obtain text content using JQuery and AJAX rather than retrieving the value

I am struggling with a dynamic table that needs to perform calculations before submitting, requiring the presence of values. However, I want to submit the text from the options instead of the values. Despite trying various approaches, none of them seem to ...

Display a confirmation modal before triggering $routeChangeStart in AngularJs, similar to the window.onbeforeunload event

When a user chooses to stay on the page as the route starts to change, the original route remains intact but the form directives are reloaded. This results in the loss of all checkbox and input values, resetting them to their defaults. If a user closes th ...

Can you identify the nature of the argument(s) used in a styled-component?

Utilizing typescript and react in this scenario. Fetching my variable const style = 'display: inline-block;' Constructing a simple component export const GitHubIcon = () => <i className="fa-brands fa-github"></i> Enh ...

Transfer the updated variable from a static JavaScript file to Next.js

I am facing a challenge with a conditional render in my component. I am unable to display the value of a variable. In one file, I have all my functions that I export in index.js import FunctionServices from "../services/functionServices" export ...

add before the beginning and after the end

Hi there, I'm trying to figure out how to add before my initial variable and after my last one. This is the code snippet: $pagerT.find('span.page-number:first').append($previousT); $pagerT.find('span.page-number:last').append($n ...

I keep encountering the error message "ReferenceError: window is not defined" in Next.js whenever I refresh the page with Agora imported. Can someone explain why this is happening?

Whenever I refresh my Next.js page with Agora SDK imported, I keep encountering the error "ReferenceError: window is not defined". It seems like the issue is related to the Agora import. I attempted to use next/dynamic for non-SSR imports but ended up with ...

Trigger the jQuery function once the external URL loaded via AJAX is fully loaded

Currently, I am in the process of developing a hybrid mobile app for Android and I am relatively new to this technology. I have two functions in jQuery, A and B. Function A is responsible for making an AJAX request to retrieve data from 4 external PHP fi ...

Filtering data from an Ajax request in Angular using a filter function with JSON

Hi everyone, I recently started learning AngularJS and created a basic item list with search functionality and pagination. Everything was working smoothly, so I decided to move my list outside the controller and store it as a JSON file. Here's what ...

What is the process for exporting an SVG file from a web page?

<svg class="paint" version="1.1" xmlns="http://www.w3.org/2000/svg"> <rect class="svgobject" x="458" y="165.28750610351562" width="142" height="56" fill="black" stroke="black" id="154" transform="translate(0,0)"> </rect> </svg> ...

Implementing a Scalable Application with React Redux, Thunk, and Saga

What sets Redux-Saga apart from Redux-Thunk? Can you explain the primary use of redux saga? What exactly is the objective of redux thunk? ...

The history.push function seems to be leading me astray, not bringing me back

Issue with History.Push in Register Component App function App() { const logoutHandler = () =>{ localStorage.removeItem("authToken"); history.push("/") } const [loading, setLoading]= React.useState(true) useEffect(()=>{ ...

Ways to customize decoration in Material UI TextField

Struggling to adjust the default 14px padding-left applied by startAdornment in order to make the adornment occupy half of the TextField. Having trouble styling the startAdornment overall. Attempts to style the div itself have been partially successful, b ...

Guide on creating 2 select inputs with distinct elements?

Imagine you have two select inputs called 'Favorite Fruits' and 'Least Favorite Fruits'. Both of them contain a list of 5 fruits. // The following code is an example to demonstrate the issue <select name='favoriteFruits'& ...

Tips for utilizing SSR data fetching in Next.js with Apollo Client

Trying to integrate the apollo-client with Next.js, I aim to fetch data within the getServerSideProps method. Let's consider having 2 components and one page- section.tsx represents component-1 const Section = () => { return ( <div& ...

Issue with retrieving JSON data through HTTP Get request on Internet Explorer, while it works fine on

Trying to upgrade a basic weather plugin by integrating geolocation services that identify a user's location based on their IP address. Smooth sailing on Chrome and Firefox, but IE seems to be causing some trouble. Any idea what might be the issue wit ...

Looking for an efficient method to initiate vagrant configuration seamlessly with just a click?

When setting up different VirtualBoxes on Linux, I rely on using vagrant. My objective is to simplify the process for my colleagues by allowing them to visit an intranet site where they can choose which VirtualBox they would like installed on their machin ...

Why isn't changing the property of a Sequelize instance having any effect?

While I've successfully used the standard instance syntax in the past, I'm facing a challenge with updating an instance retrieved from the database in this specific section of my code. ... const userInstance = await db.models.Users.findOne({wher ...

Can a callout or indicator be created when a table breaks across columns or pages?

As we develop HTML pages for printing purposes, one specific requirement for tables is to include an indicator like "Continues..." below the table whenever a page or column break occurs. Additionally, in the header of the continuation of the table, we need ...