NGRX effect in Nativescript Angular loses state when the app is suspended on iOS

While using NGRX with Nativescript Angular to manage state and fetch data from the server, I've encountered an issue when suspending the app on IOS. Whenever the app is in the middle of fetching data from the server and gets suspended, the entire process halts and loses all its states. Upon resuming the app, no data is returned. Is there any way to handle this situation?

The process follows these steps:

In component.ts (calling NGRX action to load data) -> actions.ts (triggering Effect to load data) -> effects.ts (calling service to load data from server, which gets cancelled if the app is suspended and resumed during this process)

component.ts

this.store.dispatch(new DataActions.LoadData(this.pageNumber));

action.ts

export class LoadData implements Action {
readonly type = ActionTypes.LoadData;

constructor(
    public pageNumber: number) {
        console.log('load more data action'); //This message is displayed in the log
    }
}

effect.ts

@Effect()
    loadData$: Observable<Action> = this.actions$.pipe(
        ofType<DataActions.LoadData>(
            DataActions.ActionTypes.LoadData
        ),
        mergeMap((action: DataActions.LoadData) => 
            this.dataService.getData(action.pageNumber).pipe(
                map((data: any) => {
                    console.log(data.result); //This message is not displayed in the log when the app is suspended
                    return new DataActions.LoadDataSuccess(data.result);
                }),
                catchError(err => of(new DataActions.LoadDataFailed(err)))
            )
        )
    );

dataService.service.ts

getData(pageNumber: number): Observable<PaginatedResult<Data[]>> {
const paginatedResult: PaginatedResult<Data[]> = new PaginatedResult<Data[]>();
let queryString = '?';

if (pageNumber != null) {
  queryString += 'pageNumber=' + pageNumber ;
}

return this.http
.get(this.baseUrl + queryString, {observe: 'response'})
  .pipe(
      map((response: any) => {
        paginatedResult.result = response.body;

        console.log(paginatedResult.result); //This message is not displayed in the log if the app is suspended

        return paginatedResult;
      })
  );

Answer №1

Whenever I find myself needing to preserve some of my NGRX state, I rely on ngrx-store-localstorage.

The setup is quite simple within your Angular module:

import { StoreModule, Action, ActionReducer, MetaReducer } from '@ngrx/store';

import { localStorageSync } from 'ngrx-store-localstorage';

const STORE_KEYS_TO_PERSIST = [
  'stateKey1',
  'stateKey2'
];

export function localStorageSyncReducer(reducer: ActionReducer<YourAppState>): ActionReducer<YourAppState> {
  return localStorageSync({
    keys: STORE_KEYS_TO_PERSIST,
    rehydrate: true,
  })(reducer);
}

export const metaReducers: Array<MetaReducer<YourAppState, Action>> = [localStorageSyncReducer];

@NgModule({
  imports: [
    ...
    StoreModule.forFeature('your-app', reducers, {
      metaReducers
    }),
    ...
  ],

You simply need to specify the store slices you want to synchronize - as shown in the example with STORE_KEYS_TO_PERSIST - and let the library take care of the data synchronization process.

Although I haven't personally tested it on mobile-based Angular applications, I believe it should work seamlessly without any issues.

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

Using parameters in routes in Angular 4

all I have created a new auxiliary website. Users will be directed to this site from the main site using a reference link like: I have set up the AppRoutingModule as follows: import { NgModule } from '@angular/core'; import { RouterMod ...

Tips for customizing labels for boolean filters in DevExtreme data grid

We are looking to change the filter options in the status field (last row) from true/false to Active/Inactive. While there is a coding method to achieve this, we are struggling as we are using a table template. It seems like it should be a simple task but ...

Error message in Angular Reactive Forms: Control with specified path cannot be found

My current challenge lies within the component: cabinet-clinic-form.component.ts. I am facing an issue with FormGroup validation in my clinics FormArray. Upon rendering the page, I encounter an error as shown in this screenshot. Despite attempting to dynam ...

Oops! The mighty gulp-clean frowns upon attempts to eradicate files outside its domain

Whenever I execute the command: gulp clean I encounter an error even though I tried using: gulp clean --force but it didn't work. Could someone please clarify what might be causing this issue or what mistake I am making? Your help would be greatly ...

Does Angular 16 not provide support for the agm/core module?

Encountering an issue while using Angular 16 with AgmCoreModule. The error message reads: node_modules/@agm/core/lib/core.module.d.ts:25:22 [ng] 25 export declare class AgmCoreModule { [ng] ~~~~~~~~~~~~~ [ng] This indi ...

The Exception: Angular Two ExpressionChangedAfterItHasBeenCheckedError

I have thoroughly reviewed the documentation regarding this error and I believe I comprehend the underlying cause. However, I am currently struggling to find an alternative architecture that would be suitable for my needs. Within the root component of my ...

"Error message: Trying to import a component in Angular, but encountering a message stating that the component has no exported

When creating a component named headerComponent and importing it into app.component.ts, an error is encountered stating that 'website/src/app/header/app.headerComponent' has no exported member 'headerComponent'. The code for app.headerC ...

It appears that `ngClass` is functioning properly during the initial page load, but once the user interacts with it and the expression changes, it is

I have begun my journey into learning Angular. Recently, I came across the [ngClass] directive which allows me to add and remove multiple CSS classes dynamically. However, I encountered an issue when trying to change the color of a text based on a variable ...

Transforming an Observable to a boolean using RXJS

Hey there, I'm currently working on creating a function similar to this: verify(){ return this.http.post(environment.api+'recaptcha/verify',{ token : this.token }).pipe(map(res=>res.json())); } I want to be able to use ...

Ways to implement a component service interface in Angular

My goal is to create a component that enforces certain design guidelines, particularly focusing on the constructor. //cool-header.component.ts @Component({ selector: 'cool-header', moduleId: module.id, templateUrl: './header.compone ...

Attempting to call a function with a template variable is not allowed

@Component({ selector: 'modal', ... }) export class SimpleModal { modalOpen: boolean; isModalOpen(): boolean { return this.modalOpen; } } <modal #modalRef> <div *ngIf="modalRef.isModalOpen()">...</div> </mo ...

How to dynamically inject HTML content from a child component into a different component using Angular 5

Is it possible to customize the content of a reusable header section based on the current route data in Angular? The header currently displays a title and description pulled from the route data property. My concern is how to dynamically inject different H ...

Issue with Angular2 not able to call POST method in CodeIgniter RESTful API resulting in 404 error

I am encountering an issue with my codeigniter restful API. While the GET method is working fine, I am unable to get the POST method to work from Angular2. this.api.post('quality/addeditquality', this.formdata).subscribe(data => { c ...

Tips for incorporating the design of a single Angular Material component

My goal is to utilize just one Angular material component. Unfortunately, the only reference I have for theming and styling involves using @include mat.all-component-themes($theme); This applies styling to all material components, whereas I specifically r ...

Transferring a PDF document to a server via a POST request

I have implemented a PDF upload section for users on my website and I want to send the uploaded file to an S3 bucket through a micro-service that I have developed. However, when I try to send the file from the front-end, it seems to be coming through empty ...

Angular's ngClass directive failed to be applied correctly

I am currently experimenting with the use of [ngClass] in Angular and it appears that it is not being applied as expected. Interestingly, [ngStyle] for similar CSS styles is working without any issues. What could I be doing wrong in this scenario? There ar ...

What could be causing my function to not provide the expected output?

Whenever I try to invoke the function from another part of the code, I encounter an issue where it returns undefined before actually executing the function. The function is stored in a service. login.page.ts: ngOnInit(){ console.log(this.auth.getRole()) ...

Saving a user with a BLOB avatar in Angular 5: Tips and Tricks for Success

As a newcomer to Angular, I am trying to figure out how to properly save a new user with an avatar. Can someone help me understand how to pass the Blob value of the avatar to my user Model for successful saving? Below is the code snippet I am working with ...

retrieve Angular data across components using Input

When using fetch to make a request to the reqres api users in app.component, I then share the data with its child component (hello.component) via Input. While I am able to get the correct user names in the child template, I encounter an issue when trying t ...

Ways to transfer information from HTML form components to the Angular class

I am currently working with angular 9 and I have a requirement to connect data entered in HTML forms to the corresponding fields in my Angular class. Below is the structure of my Angular class: export interface MyData { field1: string, textArea1 ...