Is real-time updating possible with data binding in Polymer and JavaScript?

I have a scenario where I am working with two pages: my-view1 and my-view2. On my-view1, there are two buttons that manipulate data stored in LocalStorage. On my-view2, there are two simple div elements that display the total value and the total value in the last 6 months.

The issue is that on my-view2, the displayed values do not update unless the page is manually refreshed. I want the values on my-view2 to automatically update every time the page is loaded or viewed, even if it's cached.

I have provided a plnkr link showcasing my-view2 so you can better understand what I am trying to achieve.

https://plnkr.co/edit/ul4T2mduxjElCN4rUUKd?p=info

Any suggestions on how I can accomplish this?

Answer №1

To trigger an update in my-view2 when localStorage is updated, you can listen to the storage event:

<my-view-2 id="myView2"></my-view-2>
<script>
  window.onstorage = function(e) {
    if (e.key !== 'someKeyYouWant') return;
    document.getElementById('myView2').set('someProp', {
      oldValue: e.oldValue,
      newValue: e.newValue
    });
  };
</script>

For a workaround due to the storage event not being triggered on the window making the change, you can manually trigger a custom storage event like this:

saveToLs(e) {
  e.preventDefault();
  const newName = this.get('dogName');
  const ls = window.localStorage;
  const synthEvent = new StorageEvent('storage');
  const eventConfig = [
    'storage', 
    true, 
    true, 
    'myDog', 
    ls.getItem('myDog'), 
    newName
  ];

  synthEvent.initStorageEvent(...eventConfig);

  setTimeout((() => { // ensure async queue
    ls.setItem('myDog', newName);
    this.dispatchEvent(synthEvent);
  }).bind(this), 0);
}

On the receiving end, handle the storage update like this:

handleStorageUpdate(e) {
  if (e.key !== 'myDog' || e.newValue === this.get('dogName')) return; 
  this.set('dogName', e.newValue);
}

Remember to use the if statement to avoid processing duplicate updates with the same value.

Feel free to experiment with this concept using this example plunk.

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

Alert: Unauthorized hook call and Exception: Cannot access properties of null (reading 'useState')

I am currently working on a project using ASP.NET Core with React. To bundle my code, I have opted to use Webpack 5. Within the index.jsx file, I have the following code: import { useState } from "react"; function App() { const [value, setV ...

Having difficulty initializing jQuery DataTables upon button click with an Ajax request

I have a piece of HTML code that represents a partial view: <table id="table_id" class="table table-inverse"> <thead class="thead-inverse"> <tr> <th>Select</th> ...

I need help getting my Vue.JS project to function properly when it is deployed on a server

After creating a new VueJS project using the Vue UI, I noticed that everything runs smoothly locally at http://localhost:8080/ with no errors. However, when I build the project and upload the files from the dist folder to my hosting package via FTP, I end ...

Creating an overlay button within various containing divs requires setting the position of the button

Tips for overlaying a button on each HTML element with the class WSEDIT. My approach involves using a JavaScript loop to identify elements with the CSS class WSEDIT, dynamically create a button within them, and prepend this button to each element. Below ...

How can a JavaScript map be created with string keys and values consisting of arrays containing pairs of longs?

Struggling with JavaScript data structures, I am trying to create a map in which the key is a string and the value is an array of two longs. For instance: var y = myMap["AnotherString"]; var firstNum = y[0][0]; var secondNum = y[0][1]; // perform opera ...

Empowering Components with React Hooks

I am currently in the process of transitioning from using class components to React hooks with the Context API. However, I am encountering an error and struggling to pinpoint the exact reason for it. Here are my Codes: // contexts/sample.jsx import React ...

php After the ajax request, the array_push function is failing to add values to the

I am having trouble with my ajax and php implementation. I want to append an array every time an ajax call is made, but it doesn't seem to be working. Here are the codes I am using: $('#multiple_upload_form' +count).ajaxForm({ ...

Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked? application.js $(document).on('ajax:success', '.follow-btn-show', function(e){ let data = e.detail[0]; let $el = $(this); let method = this ...

Is the condition failing to evaluate for all td elements?

I am currently dealing with an HTML table. When I select a checkbox, I aim to compare the values of the cells in each row. This comparison works correctly for the first row, but it does not work for any subsequent rows. HTML Code - <form role="fo ...

The filtering feature in AngularJS ng-options is not functioning correctly

Greetings, I am a newcomer to angular. In my current demo application, I have created a list of users with a select filter using ng-option. There seems to be a bug that I have been unable to identify. The issue: When I select the Female option, i ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

Tips for stopping Vue.js automatic merging of CSS classes

Recently, I embarked on my journey with Vue.js and have been thoroughly enjoying the experience. However, I've stumbled upon a challenge that has me stumped. Despite searching high and low and studying the documentation, I haven't found a solutio ...

Is it possible to use Vuelidate for password validation in Vue.js?

I found a helpful reference on How to validate password with Vuelidate? validations: { user: { password: { required, containsUppercase: function(value) { return /[A-Z]/.test(value) }, containsLowercase: fu ...

Can Typescript classes be hoisted if I use two classes in my code?

Exploring Class Definitions Certain Rules to Comply With Ensuring that the class is defined in advance helps avoid errors. class Polygon { log() { console.log('i am polygon'); } } const p = new Polygon(); // Expected: no errors p.log(); U ...

"Browser compatibility issues: 404 error on post request in Firefox, while request is

When following this tutorial on React and PostgreSQL, the app should display the JSON fetch in the bash terminal around the 37-minute mark. However, there seems to be a problem as there is no feedback showing up on the npm or nodemon servers. After tryin ...

What could be causing issues with my jQuery POST call?

I am attempting to establish authentication with a remote service using jQuery. Initially, I confirmed that I can accomplish this outside of the browser: curl -X POST -H "Content-Type: application/json" -H "Accept: appliction/json" -d '{"username":" ...

React and Redux encounter an issue where selecting a Select option only works on the second attempt, not the first

I am currently working on a React/Redux CRUD form that can be found here. ISSUE RESOLVED: I have encountered an issue where the state should be updated by Redux after making an API call instead of using this.setState. The concept is simple: when a user s ...

After the component has been initialized for the second time, the elementId is found to be null

When working with a component that involves drawing a canvas chart, I encountered an issue. Upon initializing the component for the first time, everything works fine. However, if I navigate away from the component and return to it later, document.getElemen ...

"Utilizing Javascript in an ERB view file within the Rails framework

In my .js.erb file, I need to execute a conditional statement when an ajax call is triggered. Below is the code snippet: function updateContent() { $('.organiser__holder').html('<%= escape_javascript render("filter_links") %>' ...

What steps should I take when dealing with two dynamic variables in a mediator script within the WSO2 ESB?

I'm facing an issue with my if condition - it doesn't work properly when the value is static. However, when I make `annee2` and `annee1` static (for example =2019), it works fine. Here's the code snippet: <script language="js"&g ...