The Firebase promise resolves before the collection is refreshed

Currently utilizing AngularFire for my project. I wrote some code to add a new record to an array of records and planned on using the promise then function to update the array with the most recent datestamp from the collection.

this.addRecord = function() {

    // Adding a new record based on user input
    $scope.records.$add({
        "date": (new Date()).toString(),
        "value": $scope.newValue

    }).then(function( ref ) {

        // Using underscore.last to determine the newest record
        var _newestValue = _.max( $scope.records, function(record) {
            return record.date;
        })[0].value;
        sync.$update({ 'newestValue': _newestValue });

    });

    // Clearing the input field 
    $scope.newValue = '';
}

The issue arises when the promise.then() is executed, as my local copy of $scope.records does not reflect the newly added record. While the server-side Firebase has the updated data, I'm unable to access it through iterating $scope.records immediately after adding. After the .then() completes, only then can I see the updated record in the collection.

Could it be that I am misusing the promise? I initially thought that when AngularFire triggers the .then(), it would mean that Angular had already added the record on the server as well as synced the local collection.

What is the correct approach for this scenario? I simply need a reliable way to confirm when the record has been locally added. Thank you!

Answer №1

After some trial and error, I discovered that using model.$watch was the most effective approach. This method only triggers when changes are made to the model that have been synchronized, providing a reliable way to track them.

$scope.records.$watch( watchCallback );

watchCallback = function() {
    if($scope.loadingModel) return; //Prevent updates during loading

    var _newestValue = _.max( $scope.records, function(record) {
        return record.date;
    })[0].value;
    sync.$update({ 'newestValue': _newestValue });
}

When working with AngularFire's model.$add().then(), it is important to note that it fires after the changes have been sent to the server, not necessarily when the local model is synced with the client. Therefore, using $add.then is more suitable for confirming that changes have been successfully saved.

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

Passing an array through ajax to PHP using jQuery

$.ajax({ type:"post", url:"add/sql_customer.php", data: "?title="+title+ "&customerid="+cid+ "&action=savecontract", success:function(data){ } ...

Is there a way to determine if an npm package is compatible with ES6 import syntax for importing?

Aside from reviewing the documentation of the package and trying different methods through trial and error, how can one be certain if an npm package can be imported using the ES6 import syntax? Is there a specific file within the package folder that can b ...

Angular: utilizing ng-click for dynamic variables

I am currently working on an index page that displays a table of all the 'acts' in my database. What I want to achieve is updating one of the acts without loading a new view, but rather rendering a partial just below that specific act's row ...

Expanding list selection with jQuery_hover effect

I have devised the following code. HTML <ul class="treatment-menu"> <li>Menu always visible</li> <ul class="nav-child"> <li>Hidden sub menu</li> </ul> </ul> Hover function $(&a ...

Search a database for a specific set of ObjectID using Mongoose

I'm currently developing an API using node.js, express, and mongoose. As I am still new to mongosse, I have been exploring different approaches to achieve what I need. In my database, I have two collections: users and expenses. Here's an exampl ...

What are the steps to integrate and utilize DefinePlugin within your webpack configuration?

Hello, I'm currently trying to implement the DefinePlugin in order to update the version number and ensure that my JavaScript refreshes after a new build is released. Unfortunately, I am encountering issues with getting DefinePlugin to work properly. ...

Backand.com experienced a surprise encounter with an error 404 while utilizing the REST API

Working with my web app, I've integrated Backand.com as my MBAAS provider. All tables are linked and a data model has been set up. While querying the default REST APIs poses no issue, encountering a 404 error randomly happens when attempting to call ...

javascript - A single image within the array fails to load

I'm encountering a challenge while trying to preload images in an array for later use in drawing on a canvas, such as in a 2D top-down game board. Interestingly, one of these images (which are Greyscale GIFs, by the way) refuses to load. It's evi ...

Changing the color of a menu item in Bootstrap when a modal window is closed: A guide

I am implementing Twitter Bootstrap and attempting to launch a modal popup by clicking on a menu item. Below is the code snippet: <div class="navbar navbar-fixed-bottom"> <div class="navbar-inner"> <ul class="nav pull-right"> ...

Ajax is capable of sending images as part of the data payload

I am attempting to send data via Ajax, and this data may include an image. Unfortunately, I do not have any forms, so I am unable to submit in the traditional way. Here is my HTML code: <input type="file" accept="image/png,image/jpg,image/jpeg,image/ ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

JavaScript function to evaluate true conditions

I am encountering an issue while calling sub functions connected to if statements within my main function. Even though the sub functions are supposed to return true or false, the expected alerts are not appearing. if (functionAAA()){ alert("111 ...

Displaying a 404 error page in a Vue.js and Vue Router single-page application when a resource is not

Implementing Vue and Vue Router in a single page application (SPA) has presented me with a challenge. In one of my view components, I query a repository for a specific resource. If the resource cannot be found, I'd like to display a 404 error page wit ...

Creating a Dojo HTML template involves incorporating repetitive sections of HTML code within the template structure

I am working with a custom Dojo widget that is based on a template and has an HTML template stored in a separate .html file. Here is the Dojo Widget code snippet: define("dojow/SomeWidgetName",[ "dojo/_base/declare", "dijit/_WidgetBase", "dijit/_Templat ...

Empty Data Table Search After Refresh While Filter Remains Active

After testing the data tables library using their example code in a jsfiddle, it seems like there might be a bug. To recreate the issue, follow these steps: Open the JS Fiddle link https://jsfiddle.net/t4rphnuc/ Click "Run" In any footer search box, fil ...

Creating a new pop-up window within a pre-existing pop-up window through the implementation of JavaScript

I am attempting to trigger a second pop-up from an initial pop-up using the code provided below. However, when I click on it, the first pop-up refreshes and displays the items within it instead of opening another separate pop-up window. My goal is to have ...

The use of Ajax post results in the retrieval of multiple arrays containing objects that possess various values

I have a PHP file (ajax.php) that retrieves messages from a database and a JavaScript file (main.js) that sends an AJAX request to this PHP file. My goal is to create a table row in the JS file for each message returned by the PHP file. Main.js: functio ...

Obtain variable declared in script tag (Google Chrome Extension)

I'm facing a dilemma. I need to retrieve the value of a variable defined inside a script tag in the DOM. <script id="foo"> var x = 1 </script> I tried accessing it like this: var script = document.querySelector("#foo"); But what ne ...

Enhance your website with jQuery scripts for dynamically loaded content without relying on $(document).on

Currently, I am utilizing an infinite scroll plugin in conjunction with ajax. The issue arises when the 'next page' is loaded using ajax, causing all other scripts related to ajax on that subsequent page to malfunction. Suggestions have been mad ...

Incorporate 3 additional compound filters with shuffle.js

Is there a way to add a third compound filter to the existing shuffle.js code provided below? // ES7 will have Array.prototype.includes. function arrayIncludes(array, value) { return array.indexOf(value) !== -1; } // Convert an array-like object to a r ...