Using Polymer to automatically update the DOM when a JSON file is modified

I am currently developing a modal window to add data to a JSON file and then display that data in the DOM. The issue I'm facing is that while the data gets saved to the file successfully, it doesn't reflect immediately on the DOM. The technology stack used includes iron-ajax for handling asynchronous requests.

     <div>
         <iron-ajax 
            auto
            url="areas.json"
            handle-as="json"
            last-response="{{response}}"
            on-response="responseHandler" 
          ></iron-ajax> 

          <div class="modal"></div>

        <div class="layout vertical">        
            <div class="layout horizontal">
                <template class="" id="esquema" is="dom-repeat" items="{{response}}" as="item">
                    <div class$="iron-flex {{item.type}}">{{item.name}}</div>
                </template>
            </div>
         </div>
    </div>

The snippet provided above shows how the data is fetched from the JSON file and rendered on the DOM. However, a specific function call is required to update the dom upon adding new data using the modal:

    addData: function(){
            var selectedItem = this.options[this.selectedIndex];            
            nuevo.push({"name": this.$.numberArea.value, 
                        "level": "1", 
                        "type": selectedItem.area});
            this.$.numberArea.value = null;
            this.$.areaSelect.selected = null;    
        },

In order to refresh the 'id="esquema"', I attempted calling this.$.esquema.render() within the function, but unfortunately, it didn't work as expected. Your guidance or suggestions on resolving this issue would be highly appreciated.

Thank you in advance for your support!

Answer №1

After taking the time to thoroughly review everything on my computer, I noticed a crucial mistake in your code. When attempting to use .render or .generateRequest, you were executing it within the dom-repeat template instead of the correct location, which is the iron-ajax element. The correction should look like this:

<iron-ajax 
    auto
    id="ajaxRequest"
    url="areas.json"
    handle-as="json"
    last-response="{{response}}"
    on-response="responseHandler"></iron-ajax> 

Following that, remember to include

this.$.ajaxRequest.generateRequest();
inside your function like so:

addData: function(){
    var selectedItem = this.options[this.selectedIndex];            
    nuevo.push({"name": this.$.numberArea.value, 
                "level": "1", 
                "type": selectedItem.area});
    this.$.numberArea.value = null;
    this.$.areaSelect.selected = null;
    this.$.ajaxRequest.generateRequest();
},

If we consider your current responseHandler function, it probably resembles something similar to this:

responseHandler: function(d){
    this.whereDataIsStored = d.detail.response;
}

To further enhance this functionality, you can add an asynchronous call to ensure that iron-ajax repeats periodically. This interval is specified in milliseconds, as demonstrated below:

responseHandler: function(d){
    this.whereDataIsStored = d.detail.response;
    this.async(function(){
        this.$.ajaxRequest.generateRequest();}, 5000);
},

This modification enables data storage in a property before triggering an automatic request every 5000 seconds for updated data retrieval. Ultimately, this should reflect in your dom-repeat component.

For additional information on async, refer to the provided link.

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

Incorporating library files (css/js) into your app built on the angular-fullstack framework

After using a Yo Angular-Fullstack generator (https://github.com/DaftMonk/generator-angular-fullstack) to start an app, I attempted to install Toastr from bower with the command: bower install angular-toastr Now, I need to add the toastr css and js files ...

Exploring JSON parsing using the Gson library: Tips and tricks

Having trouble parsing a JsonObject with the gson library using Maven dependencies. I cannot seem to create a map that contains the keys and values. I attempted to use the keyset method, but it cannot find the corresponding value (resulting in a null poin ...

Replacing a JSON vault using XHR: A step-by-step guide

Can someone assist me in replacing the JSON data from a JSON file on a website using JavaScript XHR? setagaya.json: {"trains":[{"operation_number":1,"line_id":26007,"station_id":784,"track_number":1,"up":true},{"operation_number":2,"line_id":26007,"stati ...

Copy the style of a chosen element and apply it to another element

One of the challenges I'm facing involves a dynamic span element that changes based on color selection: <span class="color checked" style="background-color: #ff0000">Red</span> In addition, I have an image element wit ...

When attempting to retrieve the data from a JSON file using an XMLHttpRequest, the result that is returned is [object object]

I am currently studying JSON and found a helpful guide on w3schools. Here is the code provided in the guide: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax The guide also includes a sample JSON file: https://www.w3schools.com/js/json_demo.t ...

Quick method for handling arrays to generate waveforms

I'm currently working on optimizing the code for my web application. While it functions, the performance is a bit slow and I am looking to make improvements: The main concepts behind the code are: The function retrieves the current buffer and conve ...

Controller experiencing issues with Ajax passing null value

My webpage features a dropdown menu with a list of ID's to choose from. When a customer selects an option, it should update the price total displayed on the page. To achieve this functionality, I'm working on implementing an AJAX call that will u ...

JavaScript validation for basic "select" isn't functioning as expected

I need assistance with my simple "select" validation using JavaScript. The issue I am facing is that when validating the "select" element, it does not display the select options to users after a validation error occurs. "The select option is not re-enabl ...

Discover the outcome of clicking on an object (mock tests)

I am just starting out with React and I'm unsure about when to use mocking. For instance, within the 'ListItem' component, there is a 'click me' button that reveals a dropdown for 'cameras'. Should I focus on testing what ...

Adding li elements dynamically, how can we now dynamically remove them using hyperlinks?

Please refrain from using jQuery code, as my main focus is on learning javascript. I am currently experimenting with adding li items dynamically to a ul when a button on the HTML page is clicked. Here's a sample implementation: HTML: <ul id="myL ...

Filtering records by a joined association in Rails using Ajax

My goal is to enable an end user to filter a data grid based on an associated record. The data grid currently displays a list of Activities: The model for activity.rb (the list of records) class Activity < ApplicationRecord belongs_to :student ...

The nightwatch.js script is halting operations once the test suite has been completed

Recently, I've implemented functional test automation using nightwatch.js. However, I encountered an issue where the test pauses after the test suite is completed, failing to end the process. Below is a snippet of the code: var afterSuite = function( ...

There was an error during product validation that occurred in the userId field. In the Node.js application, it is required to

I am in the process of developing a small shop application using node.js, express, and mongoose. However, I have encountered an issue when attempting to send data to the MongoDB database via mongoose. Here is the product class I have created: const mongoo ...

Show only the portion of the image where the cursor is currently hovering

Information in advance: You can check out the current code or view the live demo (hover image functionality not included) at . The concept: I would like to have it so that when I hover my cursor (displayed as a black circle) over the image, only the s ...

Creating an HTML table with colspan and rowspan using ng-repeat from a deeply nested JSON dataset

I'm working on creating a table layout shown in the attached image: Composite Class Routine Check out my progress so far in this Plunker demo: https://plnkr.co/edit/4WiWKDIM2bNfnmRjFo91?p=preview The JSON data I'm using is as follows: $scope. ...

The error `Uncaught TypeError: array_unique(): Argument #1 ($array) must be of type array, string given` suggests that the

I am encountering an issue while attempting to obtain unique values in the option menu within a select element by using the array_unique() function. However, I keep receiving the following error message: Fatal error: Uncaught TypeError: array_unique(): A ...

I'm having trouble getting jquery css to function properly in my situation

I am trying to implement a fallback for the use of calc() in my CSS using jQuery CSS: width: calc(100% - 90px); However, when I tried running the code below, it seems like the second css() function is not executing. I suspect that there might be an issu ...

No information is being emitted by the subject

In my application, I have a feature where users input data that needs to be validated in a form. Once the validation is successful, a button is enabled allowing the user to submit their order. However, I'm facing an issue with this specific component ...

How can I dynamically populate my select field with JSON data using React.js?

My goal is to fetch data from an API and use the 'symbol' JSON field as options for a select dropdown. However, I'm encountering an issue: 'TypeError: Cannot read property 'length' of undefined.' Beneath my code, I' ...

No content appears on the multi-form component in React

After several attempts at building a multi-step form in React, I initially created a convoluted version using React.Component with numerous condition tests to determine which form to display. Unsatisfied with this approach, I decided to refactor the code f ...