Angular cache options - javascript

I am new to angular and wanted to implement the cache in it. I have found few after Google http://gregpike.net/demos/angular-local-storage/demo/demo.html
http://jmdobry.github.io/angular-cache/
Can anyone suggest which is the best cache for angular. My app is a kind of ticketing system and i need to cache many drop-down list value and and view data.
i need to cache the object of the list (not html). There are few list which will change very rarely and some are that can change after a day or two. if i can cache the $http call in local storage , it would be great.

If you do not need a persistent cache then you may consider simply using the built-in AngularJS $cacheFactory.
To obtain cache persistence you would need look at using local storage. There are a number of options available however angular-local-storage is the most popular.

I'd do it with a custom cache in the service: https://stackoverflow.com/a/60190745/1974681
With this approach when you reload your app, the caché is refreshed too.
You could use localStorage or sessionStorage. In that case the cache will not be refreshed on app reload (https://alligator.io/js/introduction-localstorage-sessionstorage/).
localStorage and sessionStorage accomplish the exact same thing and have the same API, but with sessionStorage the data is persisted only until the window or tab is closed, while with localStorage the data is persisted until the user manually clears the browser cache or until your web app clears the data.
As easy as:
const data = {hello: 'world'};
sessionStorage.setItem('KEY', JSON.stringify(data));
sessionStorage.getItem('KEY'); // {hello: 'world'}

Related

Updating LocalStorage with the same data in the same time on multiple tabs causing problems

first of all i'm a beginer front end developer and i'm not a native english speaker so sorry for any mistake i made in my first question :D I'm working on project in Vue that was started by someone else. It uses websocket to display some notifications from server and i spotted a bug associated with this. The notifications are stored in object that pulls data from localStorage using VueUse's useStorage:
const state = reactive({
liveNotifications: useStorage("liveNotifications", []),
notificationsCount: 0,
});
And when data is received from ws it's being added to the beginning of the array like this:
connections.alerts.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data?.status) {
return;
}
state.liveNotifications.unshift(data);
state.notificationsCount += 1;
};
The problem is, when more than 2 tabs are opened and ws send some notifications, the localstorage starts acting weird like its trying to add the same objects over and over and notificationsCount is jumping (for example) from 2 to 3 and vice versa.
Is there any way to e.g. prevent app from updating localstorage multiple times if the data given from ws is the same on all tabs. Or maybe there's another way to make this work properly?
I've tried some solutions from web but to be honest i'm not really sure why is this happening and i didn't know what exactly i was supposed to look for so if someone has better knowledge than me and can help me understand i'm here to learn :)
The problem is: both tabs will read/write to the same "file".
The localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.
MDN - Window.localStorage
Suggestion here is to use sessionStorage instead:
[...] the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.
Whenever a document is loaded in a particular tab in the browser, a unique page session gets created and assigned to that particular tab. That page session is valid only for that particular tab.
It sounds like you need a shared worker.
Since you are receiving the same data it is reduntant to keep two connections.
You should handle your websocket connection in a shared worker, then upon receiving the data save it to the localStorage, then post a message to the tabs to update the UI.

Keeping my Selections when Refreshing page

So I have looked around and there is nothing about storing data collect on a webpage so if I refresh said page it would still have everything I either wrote of selected previously. I would like to implement this feature to my website.
If I select one of the options is selected, it filters to said option but I want that option to save on my page when website is refreshed. Is there anyway to do so???
There are many ways to do that.
First of all you can save it on server, but it to much resource cost and in most situations not good solution.
For this problem the best way to store this info on client. You can use something like cookies, session storage and local storage.
I think session and local storage are the best for your purposes. Difference between them session storage save info for current sessin - browser window, loses after browser window closed. Local storage works for browser at all, loses after cockies and storage clear (by hands). So on current computer and browser local storage would save info until it directly cleared))
Also you can use query string, but it is bad solution.
You can simple find more info about localstorage in the internet. Also popular frameworks like angularjs has services to manage work with local and session storage)
The simplest way to achive what you are looking for is with LocalStorage, which is a feature that is supported on most web browsers.
The API in javascript looks something like this:
function onClick(){
localStorage.setItem('selectedRole', role);
}
And on the page load:
$( document ).ready(function() {
selectedRole = localStorage.getItem('selectedRole')
});
You should probably edit the code a bit to fit your needs, This is how I guess you implemented your application.
In your case, sessionStorage is the best choice since you need to persist on refresh only. On page close, the data will lose.
Store the data on page refresh using:
window.onbeforeunload = function () {
sessionStorage.setItem('selectedFilter', selectedFilterData);
};
Retrieve the data on page load using:
window.onload = function () {
var selectedFilter = sessionStorage.getItem('selectedFilter');
if(selectedFilter !== null) {
//set the selections
}
};

Angularjs refresh and save data

im working in a app that makes many calculations, and basically i implemented a functionality when a user refreshed or F5 a page he will not loose his data in the current page, im saving the data in localStorage since the data isnt saved in the db, does angularjs have some kind of storage data that i could use it or does anybody no a better solution to use. (not using a database).
You can use the following ways for storing the data:
1) $localStorage
2) $sessionStorage
Given below is a simple example of how you can save an input field in localStorage and still retrieve the value on refresh
<input type="text" ng-model="myValue">
<button type="button" ng-click="saveData()">Save</button>
In controller:
//this will execute everytime on refresh
$scope.myValue = $localStorage.data || null;
$scope.saveData = function(){
$localStorage.data = $scope.myValue;
//similarly $sessionStorage.data can be used
}
You could choose between localStorage and sessionStorage.
localStorage will keep data until you will decide to clear it programmatically, or user will clear it in browser.
sessionStorage on other hand will be cleared when browser or tab is closed. Sometimes it's better solution, because you won't need to think about situations when you would have to clear localStorage.
you can use localstorage for this which an html5 api
Or
If you want to do it with angular then you better go through the following link
https://github.com/grevory/angular-local-storage
http://gregpike.net/demos/angular-local-storage/demo/demo.html

Architecture for temporary storing of values within a javascript library

I am currently writing a javascript library that wraps a REST API provided by a third party (intended to be used on server side, but wouldn't like to limit it to). One of the actions defined by the api is 'login' which gives me a session key that I need to use on further requests. Currently, everytime I go to use this library I need to login again as there is no persistence of this session key. My question is, what is the best way to persist it throughout a session?
My first instinct was to give the library a callback that would store it and a callback that would retrieve it and the implementation can determine how that session key is persisted:
var thirdPartyApi = new ThirdPartyApi({
loginCredentials: {..},
setSessionKeyCallback: function() {},
getSessionKeyCallback: function() {}
});
thirdPartyApi.makeSomeRequest('foo');
Can you recommend the best architecture for this problem?
It seems like you want to use the REST Api in a browser. There are some factors you need to take into account, such as, navigating away from the page and coming back to it later.
You can use Web Storage to store the key. There are two types, localStorage and sessionStorage. The only difference between then is that sessionStorage is deleted when the browser window is closed, while localStorage isn't. Web Storage is supported by all modern browsers and IE8+ http://www.w3schools.com/html/html5_webstorage.asp
The localStorage object can be used as such:
localStorage.setItem("bar", foo);
var foo = localStorage.getItem("bar");
localStorage.removeItem("bar");
sessionStorage object can be used the same way.
both localStorage and sessionStorage are global objects that can be accessed from anywhere, so there is no need for any special architecture on your ThirdPartyApi object.

Client side data storage

I have the following situation: the user submits a form, I fetch the data from the server via an Ajax request and displays a chart. However, I want to give the user the option to display the data in the chart in table form or export as csv after he had submitted the form.
I was wondering what's the best solution to store the data, considering that I don't want the data to persist if the user opens a new window to submit the form again for example.
The application is in Rails.
Thanks.
You have a few options:
Cookies
LocalStorage
SessionStorage
More info: https://developer.mozilla.org/en/DOM/Storage
Non-standard:
window.name can store anywhere from 1mb up to 10mb depending on the browser. This is more of a hack, but is fairly stable. You would need to implement your own accessor/setter methods on this, where localStorage and sessionStorage have API's built in.
Personally i would recommend local storage if all your users browsers support it.
Its very simple to use and you can access it using these to methods.
localStorage.getItem("Itemkey");
localStorage.setItem("Itemkey","value");
localStorage.removeItem("ItemKey");
Its always a good way to go and this means you can assign each window a differnt local storage key and even remove the item when the window is closed, or unloaded !
For reference I found this very useful: http://diveintohtml5.info/storage.html
And combine it with storing JSON objects ( http://www.json.org/js.html ) and you have a very fast,simple and easy to use solution. OR even just store a string,array or what ever is required.

Categories

Resources