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

Unable to save input from <from> in the React state object

I'm currently working on a project in reactjs where I need to store user input in the react state object. I followed an example from reactjs.com, but it seems like the input is not being stored in the state object as expected. class CreateMovieForm ex ...

Utilizing JSON and CodeIgniter within HTML elements

I am interested in creating a private chatroom using CodeIgniter and JSON format. I want the JSON data retrieved to be displayed in a list structure like <ul><li>messageinJSON</li></ul>. This formatting will allow me to customize th ...

Refreshing bootstrap modal after closing it

In my Vue application, I have implemented a Bootstrap modal which contains input fields. After entering data, submitting it, and reopening the modal, I noticed that the previous inputs are still present. However, I would like to reset all input fields once ...

Create an image on a node's backdrop using a library of graph theory/networking techniques

I have a set of data that I need to visually represent as a graph on a web browser. While creating the graph itself is not an issue, I am looking to dynamically draw unique icons for each node. These icons are specific to the characteristics of each node ...

What is the reason for the error message "vue","v-for","item is not defined"?

Here is my code in HTML. I am encountering an issue when using 'v-for' where it says 'item is not defined'. <form action=""> <div class=" form-group"> <tr> &l ...

Is it possible to use AngularJS promises without callbacks?

Typically, when I want to retrieve data asynchronously, I would use the following approach: var promise = $http.get('/api/v1/movies/avengers'); promise.then( function(payload) { $scope.movieContent = payload; }); This scenario is quite ...

Having issue updating a MySQL table using an array of objects in JavaScript

Working on a personal project involving React.js for the front-end, Node.js/express for the back-end, and mySQL for the database. The current array is as follows: horaires = [ { jour: 'Lundi', horaire: 'Fermé' }, { jour: 'Mar ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...

Utilizing $.each to dynamically add data to a jQuery Mobile listview

Trying to implement a data reading mechanism using ajax resulted in unexpected html tag generation for <ul> <li>. The code snippet is as follows: (function( $, undefined ) { $(document).on("pagecreate", ".jqm-demos", function(){ ...

What is the best way to detect component errors on the server with Angular Universal?

Here is a snippet of my server code that renders the Angular home.component: app.get("*", (req, res) => { res.render( `../${CLIENT_DIST_DIR}/index`, { req: req, res: res, providers: [ ...

Tips for keeping a Bootstrap Modal in a fixed position on the screen as you scroll

I am facing an issue with a button that is supposed to trigger a Bootstrap Modal. It seems that the modal is not visible when the page has been scrolled down. Upon clicking the button to show the modal, the background darkens as expected, but the modal its ...

What is the most effective approach for addressing errors in both the server and client sides while utilizing nodejs and express?

Seeking the most effective approach for handling errors in a response - request scenario. Here is an example of a route that receives a request: app.get('/getInfo', function (req, res, next) { let obj = {} try { obj = { ...

Can you provide a succinct explanation of what constitutes a well-defined "landing page"?

Could someone provide a clear and concise explanation of what exactly constitutes a landing page and how it should be utilized? I'm struggling to grasp the concept. Where is the optimal placement for a landing page on a website? Is it best placed o ...

Adding elements to a JSON array in JavaScript/AngularJS

Looking for help with inserting a new item "uid" into a JSON array. Here is the initial array: var testArr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}] The desired output after inserting the "uid" would be: var testArr=[{name:"nam ...

AngularJS: dependent dropdown menus

Attempting to create a cascade dropdown in Angular, I assumed it would work seamlessly with binding. Here is the code snippet: <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" req ...

Ways to display JSON objects containing nested key-value pairs

In my JSON structure, each Mealplan includes a key and a corresponding value which is an object called meal. id: 1, mealsPerWeek: { Monday: { id: 4, name: "Burger", }, Tuesday: { id: 3, name: "Salad&qu ...

What is the best way to update this payload object?

Currently, I'm developing a route and aiming to establish a generic normalizer that can be utilized before storing user data in the database. This is the function for normalization: import { INormalizer, IPayloadIndexer } from "../../interfaces/ ...

Utilizing jQuery to compute dynamic fields depending on selection in a dropdown menu

Creating a Ruby app for tracking bets, I have designed a small form that captures various details including date and match. However, the most crucial components of this form are the "stake" and "odd" text fields. To enhance user experience, I have incorpor ...

Automatically hide a label after a certain amount of time following a button click

Currently, I am working with ASP.NET and C#. Within my application, there is a registration form that includes a label to display the status of registration, either success or failure. The content of this label is determined dynamically in the codebehind ...

How can I utilize the replace function in Angular to swap out a character?

I am attempting to change the characters { and } in an HTML string to {{ and }}. However, when using the replace function, I encounter the following error: $scope.selectedtemplate.template.replace is not a function Below is my code: $scope.selectedte ...