Kibroman
Kibroman

Reputation: 41

How to delete object from firebase database

I'm trying to figure out how to delete information submitted to the firebase database. I am trying to delete information under the requests. Example

Here are my actions used to fetch the data:

export default {
async contactArtist(context, payload) {
    const newRequest = {
        userEmail: payload.email,
        message: payload.message
    };
    const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${payload.artistId}.json`, {
        method: 'POST',
        body: JSON.stringify(newRequest)
    });

    const responseData = await response.json();

    if (!response.ok) {
        const error = new Error(responseData.message || 'Failed to send request.');
        throw error;
    }

    newRequest.id = responseData.name;
    newRequest.artistId = payload.artistId;

    context.commit('addRequest', newRequest);
},
async fetchRequests(context) {
    const artistId = context.rootGetters.userId;
    const token = context.rootGetters.token;
    const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${artistId}.json?auth=` + token);
    const responseData = await response.json();

    if (!response.ok) {
        const error = new Error(responseData.message || 'Failed to fetch requests.');
        throw error;
    }

    const requests = [];

    for (const key in responseData) {
        const request = {
            id: key,
            artistId: artistId,
            userEmail: responseData[key].userEmail,
            message: responseData[key].message
        };
        requests.push(request);
    }
    context.commit('setRequests', requests);
},

};

I'm trying to set up a button that will delete the selected request object.

Upvotes: 1

Views: 464

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599591

Your code is sending a POST request, which tells Firebase to generate a unique key. From the documentation on saving data:

POST: Add to a list of data in our Firebase database. Every time we send a POST request, the Firebase client generates a unique key, like fireblog/users/<unique-id>/<data>

The delete a node, send the DELETE verb/method to that path:

const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${payload.artistId}.json`, {
    method: 'DELETE'
});

Upvotes: 1

Related Questions