Is there a way to show the contents of local storage on a webpage without having to refresh the page after clicking a button

I am encountering an issue where the contents of local Storage are not being displayed until I manually refresh the page after clicking the submit button. How can I make it so that the changes made in local Storage immediately reflect on the page without needing to refresh?

The function responsible for handling page load seems to be showing incorrect data when a button is clicked. Only by manually refreshing the page, the correct data becomes visible.

const loadData = () =>
  document.querySelector('body').addEventListener('load', displayStorage());

The event listener for saving:

notesForm.addEventListener('submit', e => {
  e.preventDefault();
  const save = (sid, spost, sdate) => {
    const obj = { id: sid, post: spost, date: sdate };
    localStorage.setItem(`${sid}`, JSON.stringify(obj));
  };
  save(generateId(), post.value, dateFormat());
  loadData();
});

Answer №1

The loadData function simply registers an event listener and does not show the data in localStorage.

To display the data, consider replacing the loadData() function call in the submit callback with displayStorage().

Answer №2

Instead of manually invoking the function, try attaching it as a handler to the load event for proper execution.

const loadData = () =>
  document.querySelector('body').addEventListener('load', displayStorage);

If you want to reload the page yourself, you can do so using location.reload.

notesForm.addEventListener('submit', e => {
  e.preventDefault();
  const saveData = (id, postContent, date) => {
    const dataObj = { id: id, post: postContent, date: date };
    localStorage.setItem(`${id}`, JSON.stringify(dataObj));
  };
  saveData(generateId(), post.value, dateFormat());
  loadData();
  location.reload()
});

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

Troubleshooting: jQuery validation malfunctioning due to empty input fields

Although it may not be a complex task, I am unable to complete it on my own. Your assistance is truly appreciated. I am encountering an issue with form validation. The validations do not seem to work as expected. When the input fields are empty, no error ...

Utilize text-to-speech technology to convert the output results into

Looking for a way to live stream a text to speech message triggered by a button press on your website? Unsure how to accomplish this with Node.js and generate the file after the button press? Let's explore some solutions together. ...

What is the most effective method for storing an object in React?

I am facing an issue with storing my Object of my Checkout-Cart in a React Variable. I attempted to use the useState Component, but unfortunately, it did not work. Here is the object that I receive from my NodeJs Backend : [ { product_uuid: '3b ...

Looking to retrieve the text content of an element using jQuery?

My goal is to use jQuery mobile to transfer a user to a linked page when they click on an <li> element, and then display an alert with the text of the list element they clicked. However, my current implementation only shows an empty alert box. < ...

Module 'prompt-sync' not found

When attempting to take user input in Node.js using the prompt module, I encountered the following error message: node:internal/modules/cjs/loader:998 throw err; ^ Error: Cannot find module 'prompt-sync' Require stack: - D:\Code\C+ ...

Showing the number of times a button has been pressed

I have written some HTML code to create a button and now I am looking for guidance on how I can use Vue.js to track how many times the button has been clicked. Here is what I have so far: <div class="123"> <button id = "Abutton&q ...

Innovative ways to design a responsive carousel with Bootstrap

My goal was to create a slider with divisions inside a bootsrap carousel, and here is what I did. However, I am looking for guidance on how to adjust it so that on screens smaller than sm (of bootstrap), there are only two divisions in one carousel, and a ...

In Backbone.js, specialized events are dispatched to cater to unique needs

In search of a sleek JavaScript animation to have some balls gracefully moving within a canvas, I aim to implement collision detection using custom events managed through Backbone.js rather than resorting to an intricate nested loop to monitor interactions ...

The jQuery method .find() is unable to locate the <option> tag and behavior unpredictably

Currently, I am working on a webpage that features a table with filtering capabilities using jQuery. The filtering functionality is achieved through a Bootstrap 4 dropdown menu where each option is assigned a specific value: <select id="inputState& ...

Setting the initial date value for an Angular Material md-datepicker to a specific date

When using Angular Material md-datepicker, by default the system's current date is set as today's date and highlighted in the calendar. However, I am looking for a way to manually set any given date as today's date instead. Please see this i ...

React: automatically close other SubMenus when a new SubMenu is opened

Is there a way to automatically close all other open SubMenus when a user opens a new SubMenu? If anyone has a solution, I would greatly appreciate the help! This is my code: Menu.tsx -> const Menu: React.FC = ({ data }) => { return ( ...

Expand the scope of the javascript in your web application to cater

I am in the process of creating a web application that utilizes its own API to display content, and it is done through JavaScript using AJAX. In the past, when working with server-side processing (PHP), I used gettext for translation. However, I am now ...

Utilizing Async/Await with an Unassigned Object

I'm facing a puzzling issue with an async/await function that refuses to assign to an object. Despite displaying the expected results in the console, when it comes to actually assigning to the object, it fails to do so. Let me elaborate below: Here&a ...

How to use Ionic 3 to automatically scroll ion-scroll content all the way to the bottom

My ion-scroll component is experiencing some challenges <ion-scroll scrollY="true" style="height: 52vh;"> {{ text }} </ion-scroll> The content inside the ion-scroll keeps expanding, exceeding the designated height. Users can manually scroll ...

Enhancing a React modal to enable user input for updating state variables

Is there a way to utilize user input from the page to dynamically create elements in a React.js application? In my app.js file, I have defined some constants at the beginning for mock data: const book1 = [ {id: uuid(), content: 'reflections&apos ...

Automatically Importing in VSCode - A Guide to Enabling Full Path Imports for Material-UI

When utilizing the auto import function in VSCode to bring in Material-UI components, it defaults to a named import from the main file: import { Button } from "@material-ui/core" Nevertheless, I prefer the auto import to be a full path import li ...

Modifying paragraph content with JavaScript based on selected radio button values and troubleshooting the onclick event not triggering

I am working on implementing a language selection feature on my website where users can choose between English and Spanish. The idea is to have two radio buttons, one for each language, and a button. When the button is clicked, the text of the paragraphs s ...

Saving a PHP array on the user's browser

I'm currently working on a website that pulls product data from a database, such as price, size, weight, etc., and displays it to the user. I am looking to enhance the user experience by adding a dropdown menu that allows users to sort the products by ...

Tips for incorporating the feature that enables the inclusion of an article onto a list

I am looking to incorporate the ListArticle component, which allows for adding an article to a list. import React, { useState } from "react"; export default function ListArticle() { const [id, setId] = useState(0); const [designation, setDesi ...

What is the method for obtaining the global coordinates of the bone's tail end in Three.js when there is no child bone connected?

If I were to retrieve the global coordinates of the head tip of the bone, it might look something like this: let worldpos_head_x = skinnedMesh.skeleton.bones[111].matrixWorld.elements[12] let worldpos_head_y = skinnedMesh.skeleton.bones[111].matrixWorld.el ...