Exploring a new approach to organizing data with LocalStorage and AngularJS

I developed an application that utilizes LocalStorage to store data.

The issue I encountered was storing a large number of objects under a single key, causing the DOM to become blocked. This is due to the necessity of parsing and stringifying the JSON data every time there is a read or write operation on the "database."

As stated in a response on a different question:

LocalStorage and JSON stringify/parse operations happen synchronously on the main thread, which can slow down the app and lead to a delay in DOM rendering.

The data insertion function in the code snippet looks like this:

$scope.recordlist = extractRecordJSONFromLocalStorage();
$scope.addRecord = function () {
    $scope.recordlist.push(
            {
                date: $scope.dateJson, 
                time: $scope.time, 
                car: $scope.carList.code, 
                driver: $scope.driverList.name,
                from: $scope.locationList.place,
                destination: $scope.locationList2.place, 
                pax: $scope.paxList,
                comments: [],
                arrival: '',
                inserted: '',
                cancelled:'',
                duration:''
            }
        );
    jsonToRecordLocalStorage($scope.recordlist);
};

Given these limitations, I need to rethink my approach to storing and retrieving data.

The current method made sense to me, as I relied on AngularJS to work with and compare the objects stored under a single key.

<div class="row msf-row" 
     ng-repeat="record in filteredRecords = (recordlist | filter:dateFilter | filter: search )" 
     ng-hide="is.cancelled && (!record.cancelled || record.cancelled === '') || has.comment && (!record.comment || record.comment === '')" 
     ng-class="{ 'msf-cancelled': record.cancelled, 'msf-commented' : record.comment}" 
     ng-hide="!record.arrival && !record.cancelled" 
     ng-show="record.cancelled">

Any suggestions on how I can migrate to a more efficient system while retaining the AngularJS functionality?

I aim to avoid reading the entire file each time and still be able to filter records effectively. Any guidance on this matter, such as recommended documentation or theories, would be greatly appreciated.

You can view a live demo of the application here.

I acknowledge that there are key concepts related to data storage and retrieval that I may be overlooking. Any resources or advice on this topic would be invaluable.

Answer №1

One potential enhancement would be to create a custom filter to replace the ng-show and ng-hide directives for displaying the data.

angular.module('myapp', []).filter('showhide', function() {

    return function(record, isCancelled) {

        var hide1 = isCancelled && (!record.cancelled || record.cancelled === '') || has.comment && (!record.comment || record.comment === '');

        var hide2 = !record.arrival && !record.cancelled;

        return !hide1 && !hide2;
    };
});

Then, you can call the filter like this:

<div class="row msf-row" 
     ng-repeat="record in filteredRecords = (recordlist | filter:dateFilter | filter: search | showhide:is.cancelled )" 
     ng-class="{ 'msf-cancelled': record.cancelled, 'msf-commented' : record.comment}">

This approach relies on loading all the data into a JavaScript variable and filtering it using your script. It is assumed that your data set is not large, ideally not exceeding 10,000 objects in the list to avoid performance issues related to rendering every ng-hide element before removal.

To manage the data, you should store the filtered list in a variable that is only read once and update the local storage object with any changes. This can be achieved by using a service to handle the data.

angular.module('myapp', []).service('dataService', function() {

    var data = ... // Retrieve from localStorage
    return {
        get: data,
        save: function(){
            // Save the 'data' variable to localStorage
        }
    }
}

In your controller, retrieve the data from the service like this:

angular.module('myapp').controller('myCtrl', function($scope, dataService){
    $scope.recordList = dataService.get();
});

By using this approach, you can manipulate the array without needing to read it again, and updates to the array can be saved using the save() method on the dataService object.

Alternatively, you could consider using pouchdb or dexie.js to handle the filtering and querying of the database directly. pouchdb is suitable for syncing data with a couchdb instance, while dexie.js may be simpler for storing data locally on the client side.

However, it is unlikely that you will outgrow the localStorage solution quickly.

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

Whenever a service is utilized, the form on my controller seems to be out of scope for the service in question

I have the following code factory: angular.module('common') .factory('_g', ['$http', '$q', '$resource', '$rootScope', '$timeout', '_o', '_u', function ($ ...

Transformation of JSON data into a structured dataframe

Investigating club participation by analyzing data retrieved as JSON through a URL request. The JSON obtained and loaded using json_loads is presented below: df = [{"club_id":"1234", "sum_totalparticipation":227, "level&q ...

Executing a Python script asynchronously from a Node.js environment

I am currently managing a node.js program that handles approximately 50 different python script instances. My goal is to implement a throttling mechanism where only 4 processes can run in parallel at any given time. Initially, I attempted to create a simp ...

In search of assistance with a persistent react.js error plaguing my work

I keep encountering an error whenever I run npm start on a new project. Does anyone have any insight on how to resolve this issue? The problem might lie within the project dependency tree rather than being a bug in Create React App. Here is what you can ...

Is there a way for me to extend an absolute div to the full width of its grandparent when it is within an absolute parent div?

Here is a structured example of my HTML and CSS: <div class="grandparent"> <div class="row">...</div> <div class="absolute-parent"> <div class="absolute-child">...</div> ...

I'm having trouble grasping the concept of serving gzip-compressed JavaScript and CSS files

Why is it important to serve compressed JavaScript and CSS files? I understand that it reduces file size, but does the browser/webserver have to decompress them to read them? It's been mentioned that the webserver handles the compression. Does this me ...

In Javascript, when trying to call Firebase database child(), it may sometimes result in the return value being "

Here is the current setup: Firebase Database: setores: { -KkBgUmX6BEeVyrudlfK: { id: '-KkBgUmX6BEeVyrudlfK', nome: 'test' } -KkDYxfwka8YM6uFOWpH: { id: '-KkDYxfwka8YM6uFOWpH', nome ...

Clicking a button in jQuery to load the Pagemethods

<script type="text/javascript"> $(document).ready(function() { $('#loadbtn').click(function() { // can 't load opts = { title: 'ABCD', series: [{ ...

The absence of the 'Access-Control-Allow-Origin' header is reported even though it is actually present

I have been attempting to send a POST request from one website to my own site. Despite allowing CORS access explicitly, every time I try to make the actual POST request, I am faced with the No 'Access-Control-Allow-Origin' header is present on th ...

Tips on restricting dates to be equal to or earlier:

I have written a code to determine if two given dates are equal or not. The code should allow for the current date to be smaller than or equal to the provided date, but it should not allow for it to be greater. var date = '10-11-2015'; var toda ...

AngularJS - Troubleshooting: Why Directive is Unable to Access Ancestor's Required Controller

To access a directive controller from an ancestor directive, I am using the require property in the "child" directive. Here is an example of how it is implemented: mmDirectives.directive('mmMapActions', function() { return { restrict : &ap ...

What is the purpose of a form that includes a text input field and a button that triggers a JavaScript function when the enter key is pressed?

<form action=""> <input id="user_input" onKeyDown="if(event.keyCode == 13)document.getElementById('okButton').click()" > <input id="okButton" type="button" onclick="JS_function();" value="OK"> </form> I'm trying to a ...

Issue with Bootstrap 5 Dropdown not toggling back

<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Creative Admin Panel</title> <link rel="stylesheet" href=&q ...

Leverage the power of npm to utilize various javascript libraries for

I seem to be a bit confused here. Currently, I have the following code snippets: import * as angular from 'angular'; import 'ts-angular-jsonapi'; Interestingly, no errors are being returned with this setup. But as soon as I try this: ...

The Shopify Pixel Extension has encountered an issue - error code 1

Looking to develop a web pixel extension for my Shopify app, I followed the official guide: While building the app, encountered this error: extensions | my-app-pixel (C:\projects\shopify\my-app-pixel\node_modules\.bin\shopify ...

I am having trouble getting the bootstrap link and css files to work on a specific URL. Can you please help me troubleshoot this issue and let me know if there are any additional files needed to

When attempting to apply the bootstrap link and css files to the URL "/list/:customListName", they are not working. However, changing the URL to "/:customListName" somehow makes it work. What is the reason behind this behavior and how can I properly style ...

The useRoutes function is returning null despite the correct pathname being provided

Check out my React code snippet! I've got the Component nestled within a micro-frontend application, which is then brought into the main app using module federation. // embedded in my microfrontend. const path = '/another-component-path'; f ...

Is there a way to cache JSON in Twig?

Currently, I am using the Slim Framework along with Twig. The cache feature in Twig seems to function properly when I output HTML content. However, it fails to work when I try to output JSON: $response->getBody()->write(json_encode($data)); return ...

Error encountered when making a post request with Angular JS and Node JS: Bad

In my development setup, I am using AngularJS on the front-end with Node.js as the server. This is how I pass data from the user interface: schatApp.controller('registerController', function($scope,$location,$http) { $scope.RegisterCredent ...

Struggling to connect CSS and JavaScript files to index.html on Heroku while utilizing Node.js

Trying to set up a Tic Tac Toe game in my app.js file, but encountering some issues with linking files in index.html. app.set('port', (process.env.PORT || 5000)) //serve static files in the public directory app.use(express.static('public& ...