save to firebase in typescript

To save data to Firebase using TypeScript, you can follow the below steps:

  1. Import the Firebase SDK and initialize the app:
index.ts
import firebase from "firebase/app";
import "firebase/database"; // for database

const firebaseConfig = {
  // Your Firebase configuration goes here
};

firebase.initializeApp(firebaseConfig);
194 chars
9 lines
  1. Create a reference to the database:
index.ts
const database = firebase.database();
38 chars
2 lines
  1. Define the data you want to save as an object:
index.ts
const dataObject = {
  name: "John Doe",
  email: "johndoe@example.com",
  age: 25,
};
87 chars
6 lines
  1. Save the data to Firebase using the set() method:
index.ts
database
  .ref("users/id123") // Set the reference for where you want to save the data
  .set(dataObject) // Save dataObject
  .then(() => {
    console.log("Data saved successfully.");
  })
  .catch((error) => {
    console.error("Error saving data: ", error);
  });
269 chars
10 lines

The set() method will overwrite any existing data at the specified location. If you want to update only specific fields of the data, use the update() method instead of set().

Hope this helps!

gistlibby LogSnag