Tips for managing local storage asynchronously

I have two files in my TypeScript application, namely:

File 1 and File 2,

In File 1, I want to save a value in local storage like this:


    private load() {
    
      return this.entityService
            .load(this.$scope.projectRevisionUid)
            .then(resp => {
              localStorage.removeItem('employeerates');
              this.$scope.employeeRates = resp.employeeRates;
              return this.refreshCostRate(...resp.employeeRates)
                .then(() =>
                  localStorage.setItem(
                    'employeerates',
                    JSON.stringify(this.$scope.employeeRates)
                  )
                )
            .then(() => this.refreshBillRate(...resp.employeeRates))
            .then(() => resp.employeeRates.forEach(erm => this.calculate(erm)))
            .then(() => DatepickerUtil.reinitializeDatepickers(this.$scope));
            })
  
    }
  

In File 2, the following code exists:


            const employeerates = JSON.parse(
              localStorage.getItem('employeerates')
            );
  
            if (employeerates && employeerates.length != null) {
              employeerates.forEach((element: any) => {
                if (
                  this.employee.getUid() === element.user.personUid &&
                  element.internalRate
                ) {
                  this.cost_rate_uom = element.internalRate * this.uom_factor;
                  this.cost_rate_per_hour =
                    this.cost_rate_uom / this.uom_factor;
                  this.cost_rate.setValue(this.ap4_cost_rate_per_hour);
                }
              });
            }
  

The issue here is that setting the local storage in File 1 is asynchronous, causing problems when trying to retrieve the data in File 2.

I am looking for a way to access the local storage value from File 1 in File 2 without using setTimeOut, as it has not solved my problem. Any suggestions on resolving this asynchronous data retrieval would be appreciated.

Update:

I have not found an alternative method of passing the data this.$scope.employeeRates from File 1 to File 2, hence I resorted to using the local storage approach. However, due to the asynchronous nature of the function

this.refreshCostRate(...resp.employeeRates)
, I need to ensure that File 2 retrieves the correct value only after this function has completed.

If there are other ways to pass data between TypeScript files, especially post the

this.refreshCostRate(...resp.employeeRates)
function call, please provide your insights. It is crucial that File 2 receives the accurate this.$scope.employeeRates value.

Answer №2

In the context of your framework usage, I am unsure about which one you are using. However, my knowledge of frameworks is limited and may not be useful in this situation. One potential solution could involve exposing the Promise object from the "file 1" code each time the rate table update is required. It is generally advised against using global variables extensively, but it only needs to be globally accessible. As long as any part of the page can access it, that should suffice; for this example, a global variable will be utilized.

So, within "file 1", you can have:

    localStorage.removeItem('employeerates');
    this.$scope.employeeRates = resp.employeeRates;
    return this.refreshCostRate(...resp.employeeRates)
      .then(() =>
        localStorage.setItem(
          'employeerates',
          JSON.stringify(this.$scope.employeeRates)
        )
      )

This code clears the rate table storage and initiates the process of fetching new rates. My suggestion would be to store the Promise globally:

    localStorage.removeItem('employeerates');
    this.$scope.employeeRates = resp.employeeRates;
    window.employeeRatesPromise = this.refreshCostRate(...resp.employeeRates)
      .then(() =>
        localStorage.setItem(
          'employeerates',
          JSON.stringify(this.$scope.employeeRates)
        )
      );
    return window.employeeRatesPromise;

Subsequently, in "file2", all actions can be performed as a .then() callback:

    if (window.employeeRatesPromise) {
      window.employeeRatesPromise.then(() => {
        const employeeRates = JSON.parse(
          localStorage.getItem('employeeRates')
        );

        if (employeeRates && employeeRates.length != null) {
          employeeRates.forEach((element: any) => {
            if (
              this.employee.getUid() === element.user.personUid &&
              element.internalRate
            ) {
              this.cost_rate_uom = element.internalRate * this.uom_factor;
              this.cost_rate_per_hour =
                this.cost_rate_uom / this.uom_factor;
              this.cost_rate.setValue(this.ap4_cost_rate_per_hour);
            }
          });
        } else {
          // handle the case when there is no data available
        }
      })
    }

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

What is the best way to rearrange (exchange) elements within an Immutable Map?

Is there a way to rearrange items within an unchangeable list that is part of a Map? Here's an example: const Map = Immutable.fromJS({ name:'lolo', ids:[3,4,5] }); I have attempted to use the splice method for swapping, as well as ...

The custom layout in NestJS version 13 failed to display

I have implemented NextJs 13 in my project for building purposes. I am trying to use CustomLayout as the primary layout for my entire website. Even though there are no errors, I am facing an issue where the CustomLayout does not display as expected. ...

Executing mailto URLs from action method

As a newcomer to MVC, I am looking to create an action method in MVC that triggers Mailto:?body=body goes here.&subject=test subject, allowing the default mail client to automatically populate the user's email. Currently, I have a List<String&g ...

In search of the mean value using PHP, jQuery, and AJAX technologies

I have successfully created a star rating system using PHP and jQuery. The issue arises when attempting to display the average rate for a specific item that I am rating; instead, the average value printed is for all items being rated. Here is my jQuery co ...

Callback Method Ajaxify

Just started using Ajaxify and so far it's been a great experience. However, I'm wondering if there is a callback function available that doesn't require any specific inputs in the script. I've searched around but haven't found wh ...

Dynamic JavaScript Banner Rotation

I am looking to create a dynamic rotating banner using Javascript for my website. The purpose of this banner is to display advertisements in the form of clickable images that change every 5 seconds. My ideal size for the banner is 728x90 pixels. I want t ...

Arranging arrays of various types in typescript

I need help sorting parameters in my TypeScript model. Here is a snippet of my model: export class DataModel { ID: String point1: Point point2 : Point point3: Point AnotherPoint1: AnotherPoint[] AnotherPoint2: AnotherPoint[] AnotherPoi ...

Leveraging constructors for injecting dependencies in Angular is a key practice for enhancing modularity and maintainability

After reviewing the Angular Official documents and various blogs, I noticed that there are two different syntaxes for Dependency Injection (DI) when used within the constructor. Sometimes this is utilized, while other times it is not. This leads to the que ...

Passing the title of a page as data to a component in Next.js

I am currently working on setting a custom title for each page within my next.js project. Here is an example of a simple Layout: const MainLayout = props => { return ( <Layout style={{ minHeight: "100vh" }}> <Head> < ...

Prisma atomic operations encounter errors when attempting to update undefined values

According to the Prisma Typescript definition for atomic operations, we have: export type IntFieldUpdateOperationsInput = { set?: number increment?: number decrement?: number multiply?: number divide?: number } Let's take a look at the Pris ...

The Typewriter Effect does not appear alongside the heading

For my portfolio website, I am using React to create a unique typewriter effect showcasing some of my hobbies. Currently, the code is set up like this: "I like to" [hobbies] However, I want it to display like this: "I like to" [h ...

Unable to establish a connection to localhost using Javascript due to net::ERR_CONNECTION_REFUSED error

My setup includes a node.js express server running my API on port 7070 and a Flask server hosting my webpage on port 5000. While I can successfully access my API from the server using curl with curl http://localhost:7070/latest, I encounter issues when try ...

Customizing the Slider Range with HTML DOM Style's BackgroundImage Attribute

I have a slider range that I'd like to modify using JavaScript. Specifically, I want to change its background-image property. To achieve this, I attempted the following script: document.getElementById("range").style.backgroundImage = "linear-gradient ...

An issue encountered while implementing a post method with fetch and Express

I'm just starting out, so I hope my question isn't too basic. My goal is to send a longitude and latitude from client-side JavaScript to a Node.js server using Fetch and Express.js. Below is the HTML code snippet: <!DOCTYPE html> <html ...

The option list in AngularJS is cleared when an option is selected

In my current project, I am developing a django-tastypie api application with angularjs as the JavaScript framework. The main part of this application involves managing curriculum objects, each containing a list of grade objects and each grade object furth ...

Angular service fails to change the object's value

Currently, I am working on a service that is responsible for setting and getting the value of an object. The issue I am facing is that even though I am successfully sending the value to the setter function, when I try to retrieve it later, the values remai ...

What is the best way to extract the elements within a form using Angular and automatically add them to a list?

Recently, I started learning Angular and decided to create a simple list feature. The idea is to input an item name and price, then click "Add item" to see it added to the list below. I have all the code set up correctly, but for some reason the name and ...

Initiate the React application with the given external parameters

I have created a React app that is embedded within a webpage and needs to start with specific parameters obtained from the page. Currently, I am passing these parameters in the index.HTML file within a div element. The issue arises when these parameters ar ...

What is the best way to simulate axios API calls in Jest for mocking purposes?

I am currently testing a Vuex action async function that calls an API using axios. However, I am facing an issue where I am getting an error message that says: "TypeError: Cannot destructure property data of 'undefined' or 'null'." 3 ...

Using JavaScript to launch a new window for a specific folder

When opening a popup window with a specific URL, I typically use the following code: $("#OpenFolder").click(function () { var url = "https://stackoverflow.com"; windowObjectReference = window.open(url, "ModulesList", " ...