Having difficulty removing a specific item from Firebase Realtime Database in React Native

I am currently working on developing a mobile app that allows users to create teams and players and save them into a database. While I have successfully implemented the team creation functionality, I am facing challenges with the deletion of individual players. I can delete an entire team, but I am unable to remove a single player. Below is a snapshot of my database for reference.

Here is the code snippet for creating a team in the database:

const createTeam = async () => {
     const userTeamRef = ref(database, 'users/' + userId + '/teams');
     const newTeamRef = push(userTeamRef);
     const newTeamKey = newTeamRef.key;
 
     
     const teamID = newTeamKey;
 
     const teamRef = ref(database, 'teams/' + teamID);
     const newTeam = {
         teamID: teamID, 
         name: teamName,
         players: players.map(player => ({
             playerID: player.playerID,
             name: player.name,
             stats: playerStats[player.playerID] || {
                 plus: false,
                 minus: false,
                 shot: false,
                 shotOnGoal: false
             }
         })),
     };
     try {
         await set(teamRef, newTeam);
         console.log('New team created successfully!');
     } catch (error) {
         console.error('Error creating new team:', error);
     }
 };
 

 const addPlayer = () => {
     const playerID = push(ref(database, 'players')).key; 
     setPlayers([...players, { name: playerName, playerID }]); 
     setPlayerStats(prevState => ({
         ...prevState,
         [playerID]: { 
             name: playerName,
             plus: false,
             minus: false,
             shot: false,
             shotOnGoal: false
         }
     }));
     setPlayerName('');
 };

Here are the deletion methods from another component:

useEffect(() => {
 const teamsRef = ref(database, 'teams');
 onValue(teamsRef, (snapshot) => {
   const data = snapshot.val();
   if (data) {
     const teamsArray = Object.values(data);
     setTeams(teamsArray);
   }
 });

 return () => {
   
 };
 }, []);

 useEffect(() => {
 if (selectedTeam) {
   setPlayers(selectedTeam.players); 
 } else {
   setPlayers([]); 
 }
 }, [selectedTeam]);

 const handleDeletePlayer = (playerID) => {
 console.log("Deleting player", playerID);

 if (selectedTeam) {
   const teamRef = ref(database, `teams/${selectedTeam.teamID}/players/${playerID}`);
   console.log(teamRef);
   remove(teamRef)
     .then(() => {
       console.log(playerID, 'successfully removed');
       
       setPlayers(prevPlayers => prevPlayers.filter(player => player.playerID != playerID));
       console.log(players);
     })
     .catch((error) => {
       console.error('Error removing player:', error);
     });
 }
};

 const handleDeleteTeam = () => {
  if (selectedTeam) {
    const teamRef = ref(database, `teams/${selectedTeam.teamID}`);
   remove(teamRef)
     .then(() => {
       console.log(selectedTeam.teamID, 'successfully removed');
       setPlayers([]);
       setSelectedTeam(null);
     })
     .catch((error) => {
       console.error('Error removing team:', error);
     });
  }
 };

And here is the sample data from the database:

{
  "-NvajG9MkZFjZXgrAn-E": {
   "name": "Canada",
  "players": [
  {
    "0": {
      "name": "Sidney Crosby",
      "playerID": "-NvajBsvVwe7bJ6kbXXh",
      "stats": {}
    }
  },
  {
    "1": {
      "name": "Connor McDavid",
      "playerID": "-NvajFnxRRfc74Vg7Ysu",
      "stats": {}
    }
  }
],
"teamID": "-NvajG9MkZFjZXgrAn-E"
}
}

Answer №1

The structure of your data doesn't align with the code you've provided to delete a player from a team. The code snippet is as follows:

ref(database, `teams/${selectedTeam.teamID}/players/${playerID}`);

However, the actual data structure looks like this:

{
  "-NvajG9MkZFjZXgrAn-E": {
   "name": "Canada",
  "players": [
  {
    "0": {
      "name": "Sidney Crosby",
      "playerID": "-NvajBsvVwe7bJ6kbXXh",
      "stats": {}
    }
  },

It seems that the playerID is not "0" as indicated, but rather "-NvajBsvVwe7bJ6kbXXh".

Given the current data structure, your only option is to:

  1. Retrieve the entire team information
  2. Remove the player from the players array using JavaScript code (e.g. utilizing filter)
  3. Update the entire array back to the database

While the above solution will work, it's not the most efficient. A better approach would be to modify your data structure to better suit this scenario:

"players": {
  "-NvajBsvVwe7bJ6kbXXh": {
    "name": "Sidney Crosby",
    "stats": {}
  }
  "-NvajFnxRRfc74Vg7Ysu": {
    "name": "Connor McDavid",
    "stats": {}
  }
}

By changing the structure so that players is no longer an array but a collection of key-value pairs where each key is a player ID, each player is uniquely identified within the team.

With this updated structure, the code you currently have to delete a player would be effective.

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

Encountered a Socket.io issue: CONNECTION_TIMED_OUT_ERROR

I'm in the process of developing a simple HTML chat program. I've set up a node server for testing, but encountering a socket error when trying to access the HTML page. This is my first experience with Node.js and setting up a server, so it' ...

How can I troubleshoot the unresponsive remove div function on my website?

My code is running fine on CodePen (link provided below), but for some reason, it's not working properly in the web browser. I am executing the code from localhost and the button isn't responding as expected. CODE Here is my Visual Studio code ...

transfer properties to a dynamic sub element

I am currently working on a multi-step form project. I have successfully implemented the form so that each step displays the corresponding form dynamically. However, I am facing challenges in passing props to these components in order to preserve the state ...

Converting image bytes to base64 in React Native: A step-by-step guide

When requesting the product image from the backend, I want to show it to the user. The issue is: the API response contains a PNG image if the product has an image, but returns a (204 NO Content) if the product does not have an image. So, I need to display ...

How can I store items in a JavaScript array so that they are accessible on a different page?

I'm running into an issue with my PHP website. Each item has a "request a quote" button that, when clicked, is supposed to add the item name to an array using JavaScript. This array should then be added to the "message" field on the contact.php form. ...

Generating Three.js canvases dynamically based on requirements (implemented with classes)

In my scenario, I have an asset inventory containing multiple assets. I am looking to implement a feature where whenever a user hovers over the assets, it triggers rendering with an OrbitController (Trackball is preferred but not feasible due to a bug). Th ...

Updating Google+ url parameter dynamically without the need to reload the page

Is there a way for a user to share a link on social media platforms like Facebook and Google+ without having to refresh the page? The user can customize the link with an ajax call, ensuring that the page remains static. Here is my code for the Google Plu ...

Could a commenting feature be seamlessly integrated directly into the video player, accessible with a simple click?

I'm exploring the idea of developing a video player that allows users to add comments directly from the player itself. Imagine this: the typical toolbar at the bottom includes standard features like seek bar, volume control, play/pause buttons, but wi ...

What is the best way to change the value of a key in a JSON Object?

I am currently utilizing _underscore library. My goal is to change the value of a specific key. var users = [{ "_id": { "$oid":"3426" }, "name":"peeter" }, { "_id": { "$oid":"5a027" }, "name":"ken" }, { "_id": { "$oid":"5999" }, ...

How can I prevent a repetitive div from appearing in a JQuery show/hide function?

Whenever I trigger my AJAX function, the loading image keeps repeating every time I click on the next page. I want to prevent this repetitive loading image and only display it once when I go to the next page. To address this issue, I created a <div cla ...

How to customize the color of Navbar pills in Bootstrap 4 to fill the entire height

Is there a way to ensure that the background of nav-items is completely filled with color rather than just partially? I attempted to use Bootstrap pills, but it did not achieve the desired effect. I also experimented with my own CSS, but encountered simil ...

Access information from a service

I have developed a new service named servcises/employees.js: angular.module('dashyAppApp') .service('employees', function () { this.getEmployees = function() { return $.get( '/data/employee.json' ); }; }); ...

Partial view remains stagnant despite successful ajax post completion

I am currently in the process of developing a system that will showcase uploaded images from a file input into a specific div within my view. (with intentions to incorporate document support in the future) The challenge I am facing is that the partial vie ...

Having trouble with changing text in a link with an onclick event?

When I click on the link, I want the text to change to the second span. However, this functionality is not working. Code var reload = false; $('#change').click(function() { reload = !reload; $('#change').click(function() { ...

Initiate an AJAX call and in the event that a particular object is found in the JSON response, proceed to send a subsequent request targeting

My objective is to make an AJAX request to a URL and expect a JSON response consisting of two objects: group_id and next_page. If the next_page object is set, I want to send another AJAX request using the value of next_page as the URL. If there is no next_ ...

Return to the main page by clicking on the link #id

I am in the process of creating a personalized Wordpress theme that consists of one main page with 8 additional sub-pages. I am wondering how I can navigate to a specific section using an ID (for example, <a href="#how">how</a>) from the sub-pa ...

Does the XMLHttpRequests have a NavigationTiming interface that can be utilized?

While the window.performance object offers insights into the performance of the browser's last page load, such as DNS lookup times, I have not come across a similar feature for Ajax calls. The overarching issue I am aiming to address is the ability t ...

Is there a more efficient method for writing my jQuery code that follows a step-by-step approach?

I have developed a step-by-step setup process that guides users through various sections. Instead of using separate pages for each step (like step1.php, step2.php, etc.), I have all the code contained in one page named setup.php. This is achieved by utiliz ...

Ensure the accurate port is specified in JavaScript to connect to a WCF service

I am working on a JavaScript project where I need to check which port number a WCF service is hosted on, out of a list of 10 different port numbers. I want to find out which port number the service responds to without any errors using AJAX JSON. Although ...

When attempting to insert a date into a MySQL database using React.js, I encountered an issue with the date format

Hey everyone, I have set the input date to dd/mm/yyyy format using moment(donors.donateDate).format('DD-MM-YYYY'). However, when I click the submit button, an error is displayed in the console stating: The specified value "23-03-2022" ...