Write a single value on Firebase database without deleting existing data

Let's suppose that we have the following object in the Firebase database:

jsx
"Erik": {

    "age": 29,
    "height": "177 cm",
    "weight": "70 kg"
    
}

Now, let's suppose that we create a new component that adds gender to this object. There are two options to write the new value to the Firebase database without destroying the existing data.

1. Use transaction()

tansaction() adds data atomically to the database.

jsx
import React, { useEffect, useState } from 'react';
import firebase                       from './Firebase';

const AddGender = () => {

    const addGender = (gender) => {
        
        firebase.database().ref('Erik/gender').transaction(value => gender)
    }

    return (
        <div className = 'Gender'>
            <button onClick = {() => addGender('female')}>Female</button>
            <button onClick = {() => addGender('male')}>Male</button>
        </div>
    );

}

export default AddGender;

2. Use set()

set() allows to add data to the database overwriting the existing path. So, first we need to get the data from the path and then overwrite it with the new data.

jsx
import React, { useEffect, useState } from 'react';
import firebase                       from './Firebase';

const AddGender = () => {

    const [age, setAge] = useState(null);
    const [height, setHeight] = useState(null);
    const [weight, setWeight] = useState(null);
    
    useEffect( () => {
        
        const fetchData = async () => {
        
            let screenshot = await firebase.database().ref('Erik').once('value');
            let person = screenshot.val();
            
            setAge(person.age);
            setHeight(person.height);
            setWeight(person.weight);
        }
        
        fetchData();
        
        
    }, []);

    const addGender = (gender) => {
        
        firebase.database().ref('Erik').set({
            
            age: age,
            height: height,
            weight: weight,
            gender: gender
            
        });
    }

    return (
        <div className = 'Gender'>
            <button onClick = {() => addGender('female')}>Female</button>
            <button onClick = {() => addGender('male')}>Male</button>
        </div>
    );

}

export default AddGender;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.