Storing user and message data with LocalStorage technology

Seeking advice on a straightforward approach to storing user data and messages. My idea is to use unique key values, such as random tokens (Ynjk_nkjSNKJN) for users, and real ids (1,2,3) for messages.

Has anyone encountered this issue before?

The goal is to ensure that localStorage remains current with new server messages without deleting any users in the process.

Thank you

Answer №1

If you want to work with "tables" in the localStorage, you can follow this approach:

//columns should be an array of column literals
function createTable(tableName, columns) {
    db[tableName] = {rows: {}, columns: columns};
}

function insertInto(tableName, row, id) {
    var newRow = {};
    for (var columnName in row) {
        if (db[tableName].columns.indexOf(columnName) === -1) {
            //invalid column
            return false;
        }
        newRow[columnName] = row[columnName];
    }
    db[tableName].rows[id] = newRow;
    return true;
}

function getIDs(tableName, where) {
    var IDs = [];
    for (var id in db[tableName].rows) {
        if (where(db[tableName].rows[id])) {
            IDs[IDs.length]=id;
        }
    }
    return IDs;
}

function update(tableName, where, what) {
    what(tableName, getIDs(tableName, where));
}

function deleteRecord(tableName, where) {
    var removeIDs = getIDs(tableName, where);
    for (var id in removeIDs) {
        //Could be done by regexes, but I am not fluent with them and I am lazy to check them out
        delete db[tableName].rows[removeIDs[id]];
    }
}

function select(tableName, where) {
    var IDs = getIDs(tableName, where);
    var result = {};
    for (var id in db[tableName].rows) {
        result[id] = db[tableName].rows[id];
    }
    return result;
}

function dropTable(tableName) {
    delete db[tableName];
}

This is a basic implementation, but you can extend it to include altering, joining, grouping, and more. The goal here is to demonstrate how to create a simple database structure. Now, let's move on to storing the database in the localStorage:

localStorage.setItem("db", JSON.stringify(db));

To access the stored database after reloading the page, you need to convert the local storage item back to an object. Here's how you can initialize db:

var db = !!localStorage.getItem("db") ? angular.fromJson(localStorage.getItem("db")) : {};

Answer №2

LocalStorage acts as a storage facility for key-value pairs, all stored in the form of strings. Each message and user is given a unique key, such as "messages" and "users", respectively.

To effectively manage this data, two separate (angular) services must be created - one dedicated to handling messages and the other designed for users. These services will interact with LocalStorage using their respective keys to carry out required tasks and operations.

If you can provide additional details, we'll be able to offer more tailored assistance.

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

Arranging information extracted from an XML document following an ajax request

Here is a snippet of XML data sample to work with: <?xml version="1.0" encoding="ISO-8859-1"?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>U ...

Error encountered in Angular $injector:unpr while attempting to initialize uibModal

I followed the ui-bootstrap tutorial to create my code. On my homepage, there is a button that triggers a modal window to open using ng-click. However, when I check the dev tools, I encounter the following error: Error: [$injector:unpr] Unknown provider: ...

Switch the custom audio control button on and off within a v-for loop

I have implemented a unique audio play/pause button in my Vue app for a list of audios. Here is how it looks: <div v-for="(post, p) in post_list"> ... ... ... <v-avatar v-if="!is_played" color="#663399" ...

Tips for utilizing useQuery in React JS class component:

Currently, I'm working on an app that is exclusively built using React JS class components. Since UseQuery only functions with function components and the Query tag has been deprecated, I'm facing some challenges in getting the data I need. Any s ...

Website errors appear on the hosted page in <body> section without being present in the code

Hello there, I have set up a debug website using my "Olimex ESP-32 POE" to send internal data via JSON, eliminating the need for Serial Output from the Arduino IDE (the reasons behind this are not relevant). #include "Arduino.h" #include <WiF ...

Creating code that adheres to the ECMAScript 5 standards

In my quest to create a JavaScript library that adheres to modern standards such as HTML5, CSS3, and ESv5, I find myself wanting to break away from the mainstream libraries like jQuery and MooTools. While these are great tools, I believe in the importance ...

Stop the child component from activating the parent's onClick event

Trying to implement Material-ui within a React project, I am facing an issue with the <IconButton> component and its onClick behavior conflicting with the parent component's behavior. Specifically, I want the <IconButton> to add an item to ...

Unable to automate the selection of a dropdown menu using Selenium WebDriver

I am currently utilizing http://www.makemytrip.com/ This is the HTML code. <div class="mrgnBot30 clearFix"> <span class="watch_icn flL"></span> <div class="widget_inner clearFix suggest_me padBot15 flL"> <h3 class="clearFix has ...

Attaching a buoyant div to the precise location of a different element

I have a unordered list (ul) with individual list items (li) that are displayed within a scrollable container. This means that only 8 list items are visible at a time, but you can scroll through them to see the others. Each list item (li) has an "edit" b ...

Counting JSON Models in SAP UI5

I am encountering a particular issue. Please forgive my imperfect English. My goal is to read a JSON file and count the number of persons listed within it. I want this result to be stored in a variable that is linked to the TileContainer. This way, whenev ...

Progressive reloading page with Jquery Ajax upload

I've encountered a strange issue with a Jquery form submit. After the upload completes, the page reloads even though the server hasn't finished processing. The server only returns a JSON success status, so it's not an issue on the server s ...

Is it advisable to utilize media queries and transform: translateY(-%) to position content above the mobile keyboard?

I've been struggling for nearly a whole day and could really use some assistance. I'm having trouble understanding how chat web apps manage to work around this particular issue. There have been numerous forum posts discussing the problem: I am tr ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Combining the powers of Nextjs and Vue

Currently utilizing Vue.js, I am now looking to leverage the Next.js framework for its SEO capabilities, server-side rendering features, and other advantages. While I do have some experience with React, my primary focus is on mastering Vue.js. Is it poss ...

Which is the superior choice: Classic Ajax or jQuery Ajax?

I have a question about using AJAX. I'm stuck between choosing traditional AJAX and jQuery AJAX. When I use jQuery AJAX, sometimes it behaves strangely in Internet Explorer. This is surprising to me because jQuery is supposed to be a cross-browser lib ...

Add HTML content individually to each item in the array

I am currently developing a plugin and I need to load a preset in order to populate a form with the relevant data. In an attempt to write concise code, I created a variable called "template" that looks like this: var Fields = '<div c ...

When using async functions in iterative processes

In my current setup, I am utilizing a for-each loop to handle a list and specifically require element n to be processed only after element n-1 has completed: let elements = ["item1", "item2", "item3"]; elements.forEach(function(element){ someAsyncFun ...

Creating a dynamic method to set data for a stacked bar chart in chart.js

In the following code snippet, you can see how my stacked bar chart is rendered using Angular: <canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]=" ...

Is it common practice to include a variable in a function with the same name as the function itself?

Is it common practice to use a variable with the same name as the function within the function itself? const sum = function(arr) { let sum = 0; for(let i = 0; i < arr.length; i++) sum += arr[i]; return sum; }; Although this code runs s ...

Validate table rows in AngularJS by adding update buttons to each row

I am currently working on a project where I need to create a dynamic table using Angular's ng-repeat. Each row in the table should be able to update or delete independently, which means I need to validate each row separately. <tr ng-repeat="item i ...