The Svelte App is able to access data from Firebase database, however, it does not

Hello fellow developers, I'm currently working on a database application using Svelte, Materialize CSS, and Firebase. I can successfully read data from the Firebase database, so it's not an issue with credentials. However, when I use the "addLink" function provided below, the database doesn't update. The alerts for the date and newLink string show up correctly. You can also find the relevant code snippet below.

function addLink() {
    alert(date.getTime());
    db.collection("links").add({ link: newLink, id: date.getTime() });
}
<script>
import GetForm from "../layout/GetForm.svelte";
import TranslateButton from "../layout/TranslateButton.svelte";
import { db } from "../firebase.js";

let arrList = [];
let newLink = "";
let date = new Date();

db.collection("links")
  .orderBy("id", "asc")
  .onSnapshot(snapData => {
    arrList = snapData.docs;
  });

function addLink() {
  alert(date.getTime());
  db.collection("links").add({ link: newLink, id: date.getTime() });
}
</script>

<div class="container right-align" style="margin-top: 30px;">
  <TranslateButton />
</div>
<div class="container" style="margin-top: 150px;">
  <div class="row">
    <div class="center-align">
      <div class="row">
        <form class="col s12">
          <div class="row">
            <div class="input-field col s10">
              <textarea
                id="textarea1"
                class="materialize-textarea"
                bind:value={newLink} />
              <label for="textarea1">Enter your URL here.</label>
            </div>
            <button
              class="btn waves-effect waves-light col s2"
              on:click={addLink}>
              Send
              <i class="material-icons right">arrow_forward</i>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="center-align">
      <GetForm />
    </div>
  </div>

  <ul>
    {#each arrList as listItem}
      <li>{listItem.data().link}</li>
    {/each}
  </ul>

</div>

Answer №1

According to the official documentation Adding a Document, the recommended method for adding documents to your collection is by using the set() function. An example provided in the Node.js documentation showcases how this can be achieved.

const newData = {
  name: 'Name of link',
  key: 'Key value'
};

const docToAdd = db.collection('links').doc('uniqueId').set(newData);

This simple illustration serves as a foundational guide to inserting a document into a Firestore collection.

Furthermore, additional resources are available below that offer insight into executing queries within Firestore:

If you found this information beneficial, feel free to reach out with any further questions!

Answer №2

Inserting a new record in Firestore Database

Are you following a specific guide for Firebase? The process of adding data to Firebase requires using the set() method instead of add()

For Automatically generated ID

If you want Firestore to generate an ID automatically, simply pass nothing as an argument to the doc() method

// Using auto-generated id
db.collection('links')
  .doc()
  .set({ link: newLink })  
  .then(() => {  
    ref.get().then(doc => {
        console.log(doc.data())  
    })
  })

For using your own custom ID

If you prefer to use your own custom ID, pass that ID as an argument to the doc() method

// Set your own custom id by passing it as an argument for `doc()`
db.collection("links")
  .doc(date.getTime())
  .set({
    link: newLink
  })

Explore more on how to add data to Cloud Firestore

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

Responding to a particular message within the Telegraf framework

I am in the process of creating a telegram bot using the telegraf framework (which is based on Node.js). I would like the bot to automatically reply when someone sends the message good morning. Despite my extensive search efforts, I have not yet been able ...

When running the command "npm install," an error message appears stating "Encountered unexpected end of JSON input while attempting to parse near '...FFso8TBG3jS7 YdtExKk'."

Currently, I am exploring TensorFlow with the help of the official guide at . In order to do so, I have retrieved the package.json and the webpack.config.js files. The content of the package.json file is shown below: { "name": "tfjs-examples-baseball- ...

The AJAX status is now 0, with a ready state of 4

Struggling to execute an AJAX call (using only JavaScript) to store a user in the database. The JavaScript file I am working with includes this code: var url = "interfata_db.php"; xmlhttp.onreadystatechange = function(){ alert('ready state &apos ...

The Google Visualization chart fails to display properly once CSS is applied

Struggling with a graph display issue here. It's quite perplexing as it works fine on older laptops and Safari, but not on Chrome or older versions of Firefox. Works like a charm on my old laptop and Safari, but fails on Chrome and Firefox (haven&apo ...

What is the best way to utilize Link navigation in order to navigate away from a blocked route in the latest version of Next.js,

DISCLAIMER: I raised this issue on the Next.js GitHub repository, but it was closed without recognition. The solution provided did not resolve my problem, leading me to seek help here. The Issue at Hand I have created a demo app (accessible here) on Code ...

When using slideToggle() in conjunction with elements created using jQuery's append(), there is no automatic repositioning

Struggling with using slideToggle(), I'm facing an issue where the DOM elements do not get pushed down as expected; instead, they overlap. Despite trying multiple versions, I haven't been able to resolve this issue. The problem arises when creati ...

Loading will continue until the webpage has finished loading

I want to incorporate a loading animation into my webpage that will be displayed until all elements have finished loading. I attempted to create a popup alert using JavaScript <script type="text/javascript> window.onload = function() { a ...

How to access an element through the router-outlet in Angular 6?

<side-navigation [navigationTitle]="navTitle"></side-navigation> <router-outlet> </router-outlet> Within my project, I have a navigation bar located in the root component. I have set up [navigationTitle] as an @Input Decorator wit ...

Sending information with JSON using POST request through AJAX with PHP

Hello everyone! I have encountered a problem with my JavaScript/jQuery code and the way PHP is handling JSON input as an array. In my rate.php file, I am using print_r($_POST) to display the data, but it seems like PHP is not recognizing the JSON input cor ...

Leverage ngRepeat alongside a conditional directive to enhance functionality

I'm currently learning AngularJS for a project and I have a model that includes elements of different types. I want to display these elements in a table similar to the example below: <table> <tr><td>nameA</td><td>...&l ...

Tips for implementing multiple associations, conditions, and includes in node.js sequelize when using findAll

Currently, I am utilizing sequelize in node.js to access a mysql DB. My goal is to perform a join operation on 3 tables with the following relationship: Person n : n Work (related through PersonWork which has foreign keys for Person and Work) Work n : n ...

Learn how to prevent the rendering of a specific section of code using JavaScript/TypeScript, similar to the functionality of *ngIf in Angular

When it comes to hiding specific parts of HTML code, using comments or CSS with display:none is one option, but these are still accessible in the developer tools. How can we leverage the features of JavaScript or TypeScript to prevent these sections from ...

The text does not display on the screen as expected

I attempted to create a calculator using vue.js. Unfortunately, I encountered an issue where the second string value does not get appended on the calculator screen upon clicking the next button. This problem arose after implementing some logic for arithmet ...

Changing the path of a polyline through code manipulation can sometimes result in a lingering phantom line

Users can edit lines on the map by dragging their vertices. When a vertex is moved, the system checks if it is near another object and attaches the line to that object if necessary. During this process, when the user moves the line, the "set_at" event is ...

How is it possible for this for loop to function properly without the need to pass the incrementing variable

I managed to compile my code and it's working fine, but there's something interesting - the variable that should reference the incrementing value is not included as an argument in the for loop. var _loop2 = function _loop2() { var p = docume ...

The function putImageData does not have the capability to render images on the canvas

After breaking down the tileset The tiles still refuse to appear on the <canvas>, although I can see that they are stored in the tileData[] array because it outputs ImageData in the console.log(tileData[1]). $(document).ready(function () { var til ...

Implementing the rendering of a nested JSON array in a Handlebars view

I have a bunch of documents stored in MongoDB like this: { "_id" : ObjectId("5a8706973e4306202c424122"), "title" : "how to make a robot?", "description" : "arif", "createdBy" : ObjectId("5a71a0ebc252020d4c127911"), "allLearningGoal ...

Keep the true number hidden in the JavaScript array

Today while working on a script, I encountered an issue when trying to test it. The script was not returning the correct value - instead, it was showing [object Object] which was not the expected output. You can see a screenshot of the problem here. To res ...

Is there a way to ensure that the vertical scrollbar remains visible within the viewport even when the horizontal content is overflowing?

On my webpage, I have multiple lists with separate headers at the top. The number of lists is dynamic and can overflow horizontally. When scrolling horizontally (X-scrolling), the entire page moves. However, when scrolling vertically within the lists, I wa ...

Executing an Ajax request to a document containing <script> elements

Recently, I developed a sample page that effectively mimics table layout pages but without relying on the traditional mobile-unfriendly table features. The structure of the page is as follows: <html> ... <body> <div type="page" ...