Preserving the state of an Angular application across page refreshes

What is the best way to maintain state persistence between page reloads? I'm not referring to state management with ngrx, but rather the scenario where refreshing the page causes user logouts, unsaved changes, and other data loss.

Initially, I considered using localStorage and initializing everything in ngOnInit() for each component, but it feels like reinventing the wheel. I'm hoping there is an existing solution or pattern that can be utilized.

Any suggestions are welcome.

Answer №1

If you're looking for a way to store your application state in localstorage, a helpful tool to check out is ngrx-store-localstorage. Here is a sample implementation taken from their website:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { StoreModule, ActionReducerMap, ActionReducer, MetaReducer } from '@ngrx/store';
import { localStorageSync } from 'ngrx-store-localstorage';
import { reducers } from './reducers';

const reducers: ActionReducerMap<IState> = {todos, visibilityFilter};

export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  return localStorageSync({keys: ['todos']})(reducer);
}
const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];

@NgModule({
  imports: [
    BrowserModule,
    StoreModule.forRoot(
        reducers,
        {metaReducers}
    )
  ]
})
export class MyAppModule {}

Answer №2

A useful method is to utilize localstorage for storing necessary items, and implement actions (especially when using ngrx) to retrieve data from localstorage, store it in the state, and allow all components to access the data through selectors or any other preferred method. I hope this solution proves helpful.

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

Input for uncomplicated changing identifier

I am looking to create types for dynamic keys that will be of type number. I have two similar types defined as follows: type UseCalculatePayments = () => { totalPayments: number; aggregate: number; condition: boolean; }; type UseCalculateCommissio ...

CLI package enables exporting API facilities

I have a mono repository containing a CLI package (packages/cli) and a web application (apps/web). I want to utilize the public API of the CLI within the web app. The CLI package is packaged with tsup: export default defineConfig({ clean: false, dts: ...

Which symbol or character corresponds to the public "get symbol" method?

While going through some Typescript code, I came across a line that is giving me trouble to understand. const symbol = Symbol.for('symbolname'); class Something { public get [symbol]() { return true; } ... } I am confused abou ...

Explaining the functionality of reserved words like 'delete' within a d.ts file is essential for understanding their

I am currently in the process of generating a d.ts file for codebooks.io, where I need to define the function delete as an exported top-level function. This is what my codebooks-js.d.ts file looks like at the moment: declare module "codehooks-js" ...

How to style Angular Material Dropdowns: Trimming the Left and Right Sides using CSS

Seeking to customize Angular Material Select to resemble a basic dropdown. Even after applying the disableOptionCentering, the dropdown list options still expand from the left and right sides (refer to Current picture below). The desired look would involve ...

Utilizing custom types in React with TypeScript and Prop-Types

Currently, I am working with a string type literal that looks like this: type MyType = 'str1' | 'str2' | 'str3'. I need one of my props to only accept this specific type, but I'm struggling to specify this in PropTypes. ...

How to smoothly transition a div from one location to another using animations in an Ionic3-Angular4 application

I'm attempting to incorporate some animation into my Ionic 3 mobile app. Specifically, I want to shift a div from one location to another. In the code snippet provided below, I am looking to move the div with the "upper" class after the timeline-item ...

How to link an image from a location outside the src folder in an Angular project

I am currently working on an online store project, and I have a specific issue with my image files being stored outside the src folder. The path to the images is within the flowersApp folder under img Is there a way for me to access these images from this ...

NextJS is currently unable to identify and interpret TypeScript files

I am looking to build my website using TypeScript instead of JavaScript. I followed the NextJS official guide for installing TS from scratch, but when I execute npm run dev, a 404 Error page greets me. Okay, below is my tsconfig.json: { "compilerOption ...

Angular 6's removeAt and trackBy functions are causing issues in updating the formArray and not reflecting the

Within a formGroup, I am adding and deleting elements from a formArray. To keep track of the ids to delete, I am using trackBy. When calling the function delete(i), it successfully removes the correct element from the formArray in the form. However, in th ...

Issue with intrinsic attributes detected in Typescript for the component

Hey, I'm encountering an issue that says, "The type '{ data: dataProp[]; }' cannot be assigned to type 'IntrinsicAttributes & dataProp'. A property 'data' does not exist on type 'IntrinsicAttributes & dataPro ...

Is there an issue with validation when using looped radio buttons with default values in data-driven forms?

Within my reactive form, I am iterating over some data and attempting to pre-set default values for radio buttons. While the default values are being successfully set, the validation is not functioning as expected. <fieldset *ngIf="question.radioB ...

The POST request is being made multiple times within the Express/Angular application, though it is unclear whether the issue lies

Take a look at my Angular code Component Section onSubmit(formValue: any) { console.log("Form Value = " + JSON.stringify(formValue, null, 4)); let newRegisteredUser = { firstName : formValue.firstName, lastNam ...

Angular's nested arrays can be transformed into a grid interface with ease

I am looking to generate a grid template from a nested array. The current method works well if the elements naturally have the same height, but issues arise when values are too long and some elements end up with different heights. <div id="containe ...

Resolving circular dependencies caused by APP_INITIALIZER

My AuthenticationService is responsible for loading the AngularFirestore and is loaded in the RootComponent. All app modules are lazily loaded within the RootComponent (which contains the main router-outlet). However, several sub-modules also load the Ang ...

Using TypeScript to create a list of object keys defined as [key: string] key/value pairs

I'm looking to define an interface in TypeScript, but I'm unsure of how to go about it. Here's what I have in mind: export interface SomeInterface { testProp:{ [key: string]: { prop1: string; prop2?: string; prop3?: string; ...

Tips for leveraging stage 3 functionalities in TypeScript?

Array.prototype.at() is currently in the proposal stage 3. Even after adding "lib": ["ESNext"] to my tsconfig.json, I encountered the error: Property 'at' does not exist on type 'number[]'. Could you shed some light ...

Avoid stopping Bootstrap Vue's events

Need help with a b-form-select control in Bootstrap Vue. Trying to execute a function when the value changes, but want the option to cancel the event and keep the original value. Complicating matters, the select is in a child component while the function ...

Tips for adjusting the item count in mat-autocomplete

For quite some time now, I've been attempting to adjust the number of items in a mat-autocomplete without any luck. My project involves using material.angular.io Below is a snippet of my code import { Component, OnInit } from '@angular/core&a ...

Issue encountered with Angular Material's md-chips and md-autocomplete: The error message "control.registerOnChange is not a

When attempting to wrap mat-chips and mat-autocomplete into a ControlValueAccessor, I encountered the following errors: InfoEditorComponent.html:17 ERROR TypeError: control.registerOnChange is not a function at setUpModelChangePipeline (forms.js:2701) ...