Is there a method to prevent data loss on page refresh by persisting data stored in a database?

I'm currently developing a commenting feature for a blog using the latest version of NextJs. The text input collects data and sends it to the 'Vercel' hosted database. I am able to successfully fetch the data from the frontend as expected.

However, when it comes to displaying the data on the frontend, everything works well until the user refreshes the page, causing the data to be lost for some unknown reasons (please refer to the attached gif). This behavior is unexpected as the data should be persistent. Could this issue be related to the fact that it's a dynamic route in a 'page route' app or maybe because the comments are displayed in a 'component' rather than on the actual page? Any help in figuring this out would be greatly appreciated. Thank you in advance.

//Code for Dynamic Route '/pages/blog/[slug].js'

import React, { useRef, useState, useEffect } from 'react';
import { getSinglePost, getPosts } from '../../lib/posts';
import { Button } from '@nextui-org/react';
import CommentBox from '../../components/Blogs/CommentBox';
import useSWR from 'swr';
import { useSession } from "next-auth/react";


const PostPage = ({ post }) => {
    // Code for handling comments and fetching data
};

//Function below gets 'post' from external api, and sets it as props

export default PostPage;
///////////////////////////////////
// Component
///////////////////////////////////

const CommentBox = ({ comments }) => {

    //comments is imported from the dynamic page as prop 

    console.log(comments);  // returns data as expected.
    return (
        // Code for rendering comments
    );
};

export default CommentBox;

Answer №1

One method you can utilize is local storage.

Exploring the concept of local storage

Local storage serves as a means of storing data locally on your computer, providing offline access to those resources. It has the capability to hold large volumes of information without the need for data transfer to a server. A key advantage of employing local storage is that there's no expiry date attached to stored data, ensuring availability at all times and in any location.

You have the ability to implement something like this:

useEffect(
()=>{
localStorage.setItem('data', data)
},[])

Subsequently, during loading, you can utilize localStorage.get to retrieve the data.

Answer №2

If you're looking for an efficient storage mechanism, I recommend utilizing the Cache API.

Compared to traditional options like localstorage and sessionstorage, Cache API offers numerous advantages. A few key benefits include:

  1. Asynchronous operations that don't hinder your main thread during read/write processes.
  2. Greater storage capacity, allowing utilization of up to 60% of disk space.

For those aiming to provide an offline experience in their app, consider integrating a ServiceWorker in the future. The Cache API is highly recommended to work seamlessly with a Service Worker

Answer №3

When it comes to storing data and the size of the payload, the best approach depends on your specific needs. If you are looking to keep track of user inputs and retrieve them when a page loads or refreshes, there are two main options:

  1. LocalStorage is a good choice for smaller data payloads that do not exceed 5MB. It provides methods like get() and setItem() to manage data storage.
  2. For larger data sets and more advanced data retention requirements, consider using a cache-based solution. While browser caches have limitations in terms of data size, you can opt for distributed object databases such as Redis or Memcached for storing significantly larger amounts of data.

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

Revamp State before redirecting using React Router Dom

In my current project, I am facing an issue with redirecting after updating the state successfully. The technologies I'm using include React 16.12.0 and React Router DOM 5.1.2. Here's the scenario: I have a button that, when clicked, should updat ...

Is it possible to prevent the late method from running during the execution of Promise.race()?

The following code snippet serves as a simple example. function pause(duration) { return new Promise(function (resolve) { setTimeout(resolve, duration); }).then((e) => { console.log(`Pause for ${duration}ms.`); return dur ...

Executing multiple Ajax requests on CodeIgniter 3 from two separate pages

I am facing a critical need for a code review and unfortunately, I am unsure of where else to seek assistance besides here. Let me outline my current task: I am working on a user profile page that is designed to showcase users' comments. Users have t ...

What could be causing my react-lightbox to not expand to full screen in next.js?

I'm facing an issue in my next.js project where I am unable to view my gallery collection as expected. When clicking on an image, nothing happens as if it's just a regular component being used. Can someone please assist me with this problem? / ...

What is the best way to add selected values from a multi-select dropdown into an array?

Attempting to populate an array from a multiple select dropdown, I've encountered an issue. Despite using splice to set the order of values being pushed into the array, they end up in a different order based on the selection in the dropdown. For insta ...

Problem with onblur and onchange events not being triggered in input tag

After encountering this issue, I came to the realization that the events onblur and onchange function properly. However, I noticed that if your page contains only ONE <input type="text" onblur="loadXMLDoc()"> Change Content</input> The behav ...

Store the visible image location in memory to be used across various sections

I'm currently developing a website with a scrolling background image feature. However, whenever I navigate to another page on the site, the animation restarts from the beginning. Is there a way to cache the position so that the animation continues sea ...

Searching for client using mqtt.js in Angular2 with Typescript yields no results

I am facing a unique issue while trying to incorporate the mqtt.js library into Angular 2 using TypeScript. Below is my app.component.ts file: import { Component } from '@angular/core'; import * as mqtt from 'mqtt'; @Component({ sel ...

Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this. Below is an example of my controller: public function index(Request $request) { ...

Is there a way to create a reusable HTTP response handler for Node.js applications?

As I work on creating a rest api for a node application, I often find myself repeating the same code structure: function(req, res, next) { databaseCall() .then( (results) => { if (results != null) { res.status(200).send(results); } el ...

JavaScript HTTP Requests

I came across this AJAX example in Stoyan Stefanov's book Object Oriented JavaScript on page 275. The example involves requesting three different files. I have a few questions that I was hoping someone could help me with! What does the line xhr.se ...

Utilizing PHP to dynamically generate href links based on radio button selection in real-time interaction with JavaScript

Currently, I am utilizing the MVC framework within Codeigniter and I have a view that contains a link. It's important to mention that the href value is generated by calling a PHP function which takes 'auth/mylogin' as a parameter: <a hre ...

How can I apply a class to the pre and code elements in Redactor?

I've been struggling for days to figure out how to add a class to the formatting option element within Redactor. By default, the "Code" formatting option wraps content in either <pre></pre> or <code></code> HTML elements. Howe ...

Troubleshooting a deletion request in Angular Http that is returning undefined within the MEAN stack

I need to remove the refresh token from the server when the user logs out. auth.service.ts deleteToken(refreshToken:any){ return this.http.delete(`${environment.baseUrl}/logout`, refreshToken).toPromise() } header.component.ts refreshToken = localS ...

Is there a method to pre-load a CSS background image so that it can still be displayed even without an internet connection?

Situation: Imagine having a web app that shows an error message when trying to perform an action but fails due to a connectivity problem. The error dialogue has a CSS class with a background image that can't load because of the connection issue, res ...

What is the CSS method for altering the color of a slider's runnable track upon selection?

Seeking assistance in changing the slider track color upon selection. Struggling to achieve the desired outcome of altering the color as it slides. CSS: /* Custom Styles */ .text-size-slider { line-height: 100%; font-size: 14px; position: relative ...

Unable to locate any NativeScript modules for tns-core-module/ui

I'm working on a {N}-Application and facing an issue with importing Images from the tns-core-modules/ui/image module. Unfortunately, it seems that the target cannot be found within the tns-core-module. This is my code snippet: import * as ImageModul ...

Push the accordion tab upwards towards the top of the browser

I am working on an accordion menu that contains lengthy content. To improve user experience, I want to implement a slide effect when the accordion content is opened. Currently, when the first two menu items are opened, the content of the last item is disp ...

`Datatables sorting feature for British date and time`

I'm currently attempting to organize a column in a table using the DataTables plugin that contains UK date and time formats such as: 21/09/2013 11:15 Implementing Ronan Guilloux's code: jQuery.extend( jQuery.fn.dataTableExt.oSort, { "uk_dat ...

Switching to Next.js

In my Next JS application, I have a div that dynamically displays the currency and price of a product when a user visits a product page. <div className="flex"> <Image src={EuroCurrency} alt="Euro Sign} /> <h1 className=" ...