handle data in LocalStorage [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
If I work with tables (using react-tabele in my case), which store lot of pages of content.

When I first open first page and put that data in localStorage, then open second page and put that data to localStorage, then open third and store data in localStorage.

How should I handle it in reverse?

When I go back to second page, should I try to get data from localStorage() without sending request for those data?

Just bring it back from localStorage and render it?
If someone can give me example of using it in example similar like my case.
I saw mdn example, but they just wanted to show when you close tab you can inherit your old setup.

If I understand correctly, it's something related to caching your data in localStorage.
You can save timestamp together when you save the data to localStorage.
And when you arrive at that page again, you could check the timestamp and decide if you will send request or reuse the data in localStorage.
For example:
// when you save the data to localStorage
localStorage.setItem(KEY, JSON.stringify({
data: YOUR_DATA,
ts: Date.now()
}));
...
// when you read the data from localStorage
// here try/catch is used because JSON.parse will be error
// when the localStorage item is nothing or incorrect json string
try {
const { data, ts } = JSON.parse(localStorage.getItem(KEY));
if (Date.now() - +ts < SOME_SPECIFIC_TIMESTAMP) {
// use data
} else {
// send api
}
} catch (err) {
// send api
}
However it depends on why you save the data to localStorage.

Related

what's the order of data when I try to get data from supabase? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 hours ago.
Improve this question
I'm using supabase database to store my data, here is one table:
myTable, then I try to use fetch method in JavaScript to get data back, the code are as follows:
const res = await fetch('-', {headers: {apikey: '-',authorization: 'Bearer -',}}); fieldVal = await res.json();
(I have omitted the link)
Then I got the data back, but the order of the data confused me,
data
So, why the data of id equals 5 is the last data? Shouldn't be after the data of id equals 4?
This is my first time to use supabase, and I have scanned the docs and API, but it's a lot of other stuffs, I can't precisely locate the information I need.
You can order your query using supabase-js: https://supabase.com/docs/reference/javascript/order
const { data, error } = await supabase
.from('countries')
.select('id', 'name')
.order('id', { ascending: false })

how to find same website is opened more than two times using localStorage / cookies [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I want know whether the user has opened the website two / more tabs of the same window. If the user does so, I want to uniquely identify each website.
Create a cookie that stores a token with a random value each time the web page is loaded.
Every few seconds, submit an XMLHttpRequest to your server and include that token, along with the session value of the user.
When your server receives this request, write it to a database that keeps track of the last time that token was submitted. At the same time, check to see if the user had submitted any other requests with a different token within the past 10 or so seconds. If yes, then you know they multiple tabs open.
This is a rough answer and you'll have to implement some processes of your own to clean up the tokens, etc, but you get the idea.
Maybe something like this could work if you only need the info on the browser side.
window.addEventListener("beforeunload", function(e){
var count = window.localStorage.getItem('num_windows');
if(count != null) {
count = parseInt(count) - 1;
window.localStorage.setItem('num_windows', count);
}
}, false);
var count = window.localStorage.getItem('num_windows');
if(count == null) {
window.localStorage.setItem('num_windows', 1);
} else {
window.localStorage.setItem('num_windows', parseInt(count) + 1);
}

how can I retrieve data from Firebase in web using javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can I retrieve data from Firebase and add to html page?
and, How can I open new html pages automatically to add the data I was retrieving it?
example:
I have this course from firbase:
this key I was pushing it .
and I want my website like this course :
When I click this courses I want to see all data about this course like this :
Can anyone help me ?!
I won't like this style just I want to know how can i retrieve data and add it in new html pages in the same style in all courses .
You can retrieve data from a firebase realtime database like so:
// Import Admin SDK
var admin = require("firebase-admin");
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("path/of/your/information");
// Attach an asynchronous callback to read the data at our posts reference
ref.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
See Official Documentation here
Note: requires Node.js / npm

Is it good to return everything in 1 json? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Below is my json which is return from a web service :
{
"variantId": 100,
"tests": [
{
"testId": 15,
"attachments":[],
"attachmentLogs":[],
"flag" : true
},
{
"testId": 16,
"attachments":[],
"attachmentLogs":[],
"flag" : true
}
]
},
{
"variantId": 200,
"tests": [
{
"testId": 15,
"attachments":[],
"attachmentLogs":[],
"flag" : true
},
{
"testId": 16,
"attachments":[],
"attachmentLogs":[],
"flag" : true
}
]
}
Right now my web service method doesnt returns attachment and attachmentLogs in my json but each test will have a list of attachment and attachmentLogs and for every variant it will be different.
For Eg: VariantId=100 and testId=15 will have different attachment and attachmentLogs.VariantId=200 and testId=15 will have different attachment and attachmentLogs.
Now if user want to see attachments and attachmentsLogs for VariantId=100 and TestId=15 then user click on button and i make a 2 server calls to get attachments and attachmentLogs every time when user clicks on button.
So here my question is should i get attachment and attachmentLogs in my huge json only or right now what i am doing is the better way.
Actually i am thinking like having a such huge json doesnt add any performance overhead on browser or doesnt put any load on browser.
Can anybody suggest me what will be the better way to handle this scenario??
If you need these logs/attachments each time when you are calling your service, you can add them, but if they are optional it will be better to add just references with IDs/URLs of these huge files to fetch them if necessary by separate requests.
In this case you will have faster response time and will not send unnecessary data on each request to the service.
If you only want to show the attachments and their logs when the user clicks the button then your current solution is good.
Because, If you get all the attachment and attachment logs at once, you will have the data but that data may not be used at all, so loss of resources.
If suppose there are 50 variants and user is interested only in 2 of them, then why get data for all.
But if you can implement a pagination kind of thing, the other solution would make sense. Suppose you show only 5 variants at a time, the next five on the next api call, it would be better to have all the data at once.

How do i perform an api call in php every 5 seconds asynchronously [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm developing a live-score website, and my goal is to refresh an API request every 5 seconds and cache it in (since I only have 1000 requests per hour) and update parts of the website based on the changes of the API every 5 seconds.
The API request is done in PHP and so is the sorting of the data. However, I've been struggling with implementing the updating part of the API request. I want my API request to update in the background, and some JavaScript to update the website on a 5 second basis so I can get the new data every 5 seconds.
I would love to get some help. I wanted to do things in CRON, but the host doesn't provide to run CRON every 5 seconds. Any solutions to my problem?
You can do it without cron. Something like this would work:
User's browser sends a request to your API;
Your API checks if a value exists in cache (Memcached?), if it does - serve from cache;
If there is no cache entry, your API makes an outgoing request, sorts/processes reply and then caches it with expiration time of 5+ seconds
Advantage as compared to a cron solution - if there are no active users on your website, there are no needless outgoing requests.
You may also consider use of websockets on browser side.
The simplest way would simply to run the php script in an endless loop rather than trying to run it afresh every 5 seconds.
Something like:
#!/usr/bin/env php
<?php
while (true) {
CacheStuff();
sleep(5);
}
Then trigger it in cron using something like flock to prevent it running more than once.
* * * * * flock -n /var/lock/cache_script.lock /path/to/myscript.php
my assumption:
you dont have any opportunity for cron, memcached, redis etc (basic hosting problem)
sample
you can save data to a file as json object.
for example your file name is "5min-data.json"
so your code can be;
$timeout_sec = 5;
$file_path = '5min-data.json';
if (file_exists($file_path) && ((filemtime($file_path) - time()) < ($timeout_sec * 60))) {
$data = json_decode(file_get_contents($file_path), true);
}
else {
//produce your data here as array, it is only sample
$data = [
'brand' => 'Mazda',
'model' => 'Mzd3',
'year' => 2016,
'weight' => 1234.5,
'airbags' => [
'front-left',
'front-right',
'back-left'
]
];
file_put_contents ($file_path, json_encode($data));
}
//$data is fresh

Categories