Sveltekit: Troubleshooting problem of refreshing when utilizing store and localStorage

I am currently working on persisting data using localStorage and have successfully achieved persistence. However, I notice that when I refresh the page, it initially displays a value of 0 before fetching the localStorage value. Is there a way for me to instantly display the localStorage value without showing 0 first? Or is this not possible?

Below is my code for storing:


import { clickPower } from "$lib/store";
import { browser } from "$app/environment";

/** This tracks the highest total count of kebabs **/
export function createHighest() {
    const { subscribe, set } = writable(0);

    return {
        subscribe,
        set: (value: number) => set(value),
        reset: () => set(0),
    };
}

/** This tracks the total kebab count **/
export function createTotal() {
    const localTotal = browser && localStorage.getItem("totalKebabs");
    const totalStore = writable(localTotal ? parseInt(localTotal) : 0);
    const { subscribe, set, update } = totalStore;

    return {
        subscribe,
                 // Additional functions can be added here
        ....
    };
}

Here is the code to display the kebab count:

    
{#key $totalKebabs}
    <span>{$totalKebabs}</span>
    Kebabs
{/key}

Answer №1

To prevent mismatch between initial server sent data and storage on the page, consider disabling server-side rendering.

Another alternative is to make the store asynchronous, although this may lead to poor user experience due to delayed updates on the page.

An option could be storing information in a separate location accessible during server-side rendering for seamless integration.

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

An instance of an object is being added instead of parameters

I'm having some trouble making a server call using promises. Whenever I try to add my parameters, they end up showing as 'object%20Object' Here's the code snippet for the call: import { Injectable } from '@angular/core'; imp ...

Is there a way to combine Vue3, Stripe, and Typescript for seamless integration?

I am currently developing a Vue3 application and running into some issues while trying to integrate Stripe. I am facing difficulty in incorporating it successfully. Here is the code snippet from my Vue3 component named Checkout.vue: <template> .... ...

Integrating Auth0-js with the usePostMessage functionality

Encountering difficulties when compiling an Angular application that incorporates the auth0-js package. The code utilizes the method renewAuth(options: RenewAuthOptions, callback: Auth0Callback<any>): void;, yet it seems to be causing issues as the p ...

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...

Error: The JSON file cannot be located by the @rollup/plugin-typescript plugin

I have recently set up a Svelte project and decided to leverage JSON files for the Svelte i18n package. However, I am facing challenges when trying to import a JSON file. Although the necessary package is installed, I can't figure out why the Typescri ...

A reference to 'this' is not permissible within a static function in Types

Based on this GitHub issue, it is stated that referencing this in a static context is allowed. However, when using a class structure like the following: class ZController { static async b(req: RequestType, res: Response) { await this.a(req) ...

Manipulate the elements within an array, make changes, and then insert

In the array called newData, I am trying to add one more element with Rank 1. However, the issue is that the Rank value is getting updated for both records. The desired behavior is to have Rank set to 1 for the second record and have the first record' ...

Is Angular CLI incorrectly flagging circular dependencies for nested Material Dialogs?

My Angular 8 project incorporates a service class that manages the creation of dialog components using Angular Material. These dialogs are based on different component types, and the service class is designed to handle their rendering. Below is a simplifie ...

Using TypeORM to update a relation and set it to NULL

My challenge involves managing this specific Entity @Entity({ name: 'orders' }) export class Order { ... @ManyToOne(() => BulkOrder, (bulkOrder) => bulkOrder.orders) bulkOrder?: BulkOrder } In my update process, I am attempting to re ...

If you're trying to work with this file type, you might require a suitable loader. Make sure you

Attempting to utilize Typescript typings for the Youtube Data API found at: https://github.com/Bolisov/typings-gapi/tree/master/gapi.client.youtube-v3 Within the Ionic framework, an error is encountered after running 'Ionic Serve' with the follo ...

Trouble with Displaying Events on React Big Calendar with Typescript

Struggling to implement React Big Calendar with TypeScript. Managed to get the calendar to display correctly after adjusting the height, but unable to show any events. The array of events is populating as expected, and I modified the code for TypeScript co ...

I am facing an issue with Nestjs where it is unable to resolve my dependency, despite the fact that it is readily available within the

Encountering the following error: Error: Nest is unable to resolve dependencies of the CreateGroupTask (TaskQueueService, GroupsService, ?, GroupNotificationsService, GroupRepository, Logger). Please ensure that the argument dependency at index [2] is avai ...

Explore the capabilities of the Angular Ng2SearchPipeModule to enhance your search input

I used the ng2SearchPipeModule for an input search, but it's not working. I can't seem to find my error. In my HTML, all my books are within divs. Will typing a book title display all the divs? Of course, I have imported in app.module.ts Ng2Sear ...

What could be the reason for certain Angular modules importing successfully while others fail to do so?

I am encountering an issue with a module that I am struggling to import. Using Typescript 2.7 and Node 10 The pxl-ng-security module is showing an error in both VSCode and VS2019. When hovering over it, error 2307 is displayed. Below is the import secti ...

Exploring the methods of connecting with data-checked and data-unchecked attributes in Angular

Utilizing a toggle switch, I am able to determine what text to display in the div by utilizing html attributes such as data-checked and data-unchecked. In addition, I have an Angular pipe that translates all texts on the website based on the selected lang ...

The module named "tapable" does not contain an export for the item "Tapable"

While developing a WordPress plugin for a custom Gutenberg block, I encountered a challenge. I needed to incorporate additional scripts in TypeScript and opted to use "$ tsc --watch" along with a "tsconfig.json" file for compilation. Upon installing @word ...

What is the process of declaring a variable within a class in TypeScript?

When setting up an instance variable inside my Angular component like this: @Component({ selector: 'app-root', templateUrl: './app.component.html', //template: `` styleUrls: ['./app.component.css'] }) export class AppCo ...

Using sl-vue-tree with vue-cli3.1 on internet explorer 11

Hello, I am a Japanese individual and my proficiency in English is lacking, so please bear with me. Currently, I am using vue-cli3.1 and I am looking to incorporate the sl-vue-tree module into my project for compatibility with ie11. The documentation menti ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

What is the best way to convert a recordset to an array using React?

I'm attempting to create an array by retrieving data from a SQL recordset: +------------+------------+------------+ | start_type | field_name | start_text | +------------+------------+------------+ | 0 | Field1 | some text. | +----------- ...