My JavaScript program maintains global arrays that persist data even after refreshing the page

I am working on creating a dynamic todo list where new items can be added using a form. The issue I am facing is that when the page is refreshed, the existing data in the array persists, which is not the desired behavior.

What I want is for the previous data to be cleared every time the page is refreshed and only fresh items to be added to the array. However, currently, I have to restart the server each time to achieve this result.

initial list:
li1
li2
li3

after item addition:
li1
li2
li3
li4
li5

after refresh: (expected)
li1
li2
li3

after refresh: (actual o/p) 
li1
li2
li3
li4
li5

Snippet of my code:

const express = require("express");
const bodyParser = require("body-parser");
const app = express();

var Item = ["Home List","Shop List","Bucket List"];

app.use(bodyParser.urlencoded({extended:true}));

app.set("view engine","ejs");

var options = {
    weekday:"long",
    day:"numeric",
    month:"long"
};

app.get("/", function (req, res) {
  var today = new Date();
  var currentDay = today.toLocaleDateString("en-US",options);
  res.render("lists",{
      day: currentDay,
      newListItem : Item 
});

});

app.post("/",function(req,res){
    Item.push(req.body.newItem);
    res.redirect("/");
});


app.listen(3000, function () {
  console.log("Server running on port 3000");
});

Answer №1

In order to achieve this, one would need the capability to differentiate between a browser making a GET request for / due to the user hitting refresh and a browser making a GET request for / for any other reason … but HTTP isn't really designed for such distinctions.

The term "Refresh" simply means "Give me the most recent version of this resource". It does not imply that the resource should change in response to the request (unless the resource is a page displaying real-time information like the current time … in which case, the change is triggered by the passing of time rather than the refresh itself).

If you wish to reset the array, create an endpoint specifically intended for resetting it, then provide the user with a form and submit button that POSTs to that URL.

app.post("/reset",function(req,res){
    Item = ["Home List","Shop List","Bucket List"]
    res.redirect("/");
});

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

There was an error with the response code of 500 on the development server for react-native

An issue has been encountered on the node.js window: error: bundling failed: Error: Unable to resolve module react-native-gesture-handler from node_modules\@react-navigation\native\src\Scrollables.js: react-native-gesture-handler could ...

Issues relating to the total count of pages in the uib-pagination component of AngularJS

While there is a previous thread discussing a similar topic Calculating total items in AngularJs Pagination (ui.bootstrap) doesn't work correctly, it does not address my specific issue and I am unsure how to contribute to it. We are using a complex s ...

Exploring the Inner Workings of setInterval During React Re-Rendering

Struggling to understand how setInterval works in React while creating a countdown timer app. Despite using clearInterval in my code, the timer kept running even when paused with onPause(). let startTimer; const onStart = () => { startT ...

The issue arose as a result of a SQLITE_ERROR, specifically mentioning that the Users table does not exist. However, the model has been

Greetings! I am currently facing an issue while trying to integrate the "sequelize-typescript" library into my Express.JS REST API that I developed using Dependency Injection. The error I am encountering is: SQLite Error: no such table: Users Below is th ...

Encountering an issue with setting up Firefox profile in protractor when using selenium webdriver configuration

var p = require("p"); var ChromeProfile = require("chrome-profile"); var createChromeProfile = function(settingsMap) { var deferred = p.defer(); var chromeProfile = new ChromeProfile(); for (var k in settingsMap) { chromeProfile.setSe ...

Is there a way for me to get live updates during a lengthy asynchronous process?

I am currently developing a small web application for internal use, where users input form data that is then used to generate an Excel file sent via email. One challenge I am facing is implementing real-time updates for the user as the process can vary in ...

Shuffling a string array in a random order

I'm looking to shuffle a list of 10 names in an array: String[] names={"name 1", "name 2", "name 3", "name 4", "name 5", "name 6", "name 7", "name 8", "name 9", "name 10"}; Any suggestions on which function I could use for this task? ...

Incorporating Dynamic Component Imports in Vue.js Data and Computed Properties

I have a component called 'Page' that needs to display another component retrieved via props. Currently, I am able to successfully load my component by hardcoding the path in the data like this: <template> <div> <div v-if=" ...

Transform an array through reference manipulation

From my MySQL database, I am fetching a nested array structure Array ( [0] => Array ( [page] => categorypropose [value] => baby-sitters [id] => 357960 ) [1] => Array ( [page] => categorysea ...

Horizontally align the list items within a div that has overflow:auto

Currently, I am working on a timeline project and have the following code: $("#time-line-selector ul li a").click(function(event) { event.preventDefault(); $("#time-line-selector ul li a").removeClass("active"); ...

Is there a way to incorporate CSS or tables when converting HTML to PDF using JavaScript?

While working on a project, I successfully converted an HTML file into a PDF. However, the output did not display the CSS design. Can anyone provide suggestions on how to include CSS design in the PDF file? Below is the JavaScript function code: $(funct ...

Authorization missing in Select2 Ajax request

Encountering an issue while attempting a get request to a secure endpoint that requires an Auth token. Despite fetching the token asynchronously from chrome.storage, it fails to be included in the ajax request and results in a 401 error ("Authorization hea ...

Integrating information from various sources to create a cohesive online platform

I am looking to incorporate data from various sources into a single web page: Social networks (Facebook, Twitter, LinkedIn, etc.) RSS feeds Article meta tags (particularly OpenGraph and Twitter cards) This data may change dynamically based on user inter ...

Issue with Three.js: Animation does not appear to be functioning

I have encountered an issue with animating an object that was exported using the blender plugin from Blender to THREE.js. The animation does not seem to start running as expected... Despite trying various combinations of settings during export from Blende ...

Combining the value of $(this) to create an identifier name

I am attempting to create a hover effect on an h1 element that triggers the glowing effect on a span element with an id that corresponds to the value of the h1. While I have successfully set up a glowing effect for a sentence, I am struggling to replicate ...

Use JavaScript to illuminate individual words on a webpage in sequence

Is there an effective method to sequentially highlight each word on a web page? I'm thinking of breaking the words into an array and iterating through them, but I'm not sure what the best approach would be. I have experience with string replacem ...

Certain scripts fail to load properly when using Internet Explorer

The code snippet provided only seems to be functional in Firefox, where it displays all alerts and successfully executes the displayUserLanding function. However, in Internet Explorer, the browser appears to only execute the following alert: alert("Helper ...

I have a parent DIV with a child DIV, and I am looking to use jQuery to select the last child DIV. The parent DIV has an

In my HTML code, I have a parent div called "allcomments_4" which contains several child divs with unique IDs (oneEntry), each with their own children. My goal is to locate and retrieve the content inside the last child of the parent node (lastComment) and ...

Tips on attaching the main element of a partial view

I have a scenario in my ASP.NET MVC project where I need to render a partial view once in the main view, and then upon clicking the add button, I want to append the entire partial view to the form. However, when I click add, only the child element is added ...