Can't configure ngrx-store-localstorage for standalone components approach in Angular

30 views Asked by At

I can't seem to configure the ngrx-store-localstorage for an application using the standalone components approach. To simplify and understand the problem I created a new very simple application with ngrx and installed ngrx-store-localstorage. Here's what I did:

Post2.reducer.ts:

import { ActionReducer, createReducer, on } from '@ngrx/store';
import { Post } from '../posts1/posts1.type';

import * as postActions2 from './posts2.actions';
import { localStorageSync } from 'ngrx-store-localstorage';

export const initialValues: Post = {
  text: 'Welcome',
  likes: 0,
};

export const postReducer2 = createReducer(
  initialValues,
  on(postActions2.CHANGE_TEXT2, (state, action) => ({
    ...state,
    text: action.payload,
  })),
  on(postActions2.RESET2, () => initialValues),
  on(postActions2.UPVOTE2, (state) => ({
    ...state,
    likes: state.likes !== undefined ? state.likes + 1 : 0,
  })),
  on(postActions2.DOWNVOTE2, (state) => ({
    ...state,
    likes: state.likes !== undefined ? state.likes - 1 : 0,
  }))
);

export function localStorageSyncReducer(reducer: ActionReducer<Post>): ActionReducer<Post>{
  return localStorageSync({keys: ['post'],rehydrate: true,storage: sessionStorage})(reducer);
}

Posts2.actions.ts:

import { createAction, createFeatureSelector, props } from '@ngrx/store';

export const CHANGE_TEXT2 = createAction('[post] update2', props<{payload: string}>());
export const RESET2 = createAction('[post] reset2');
export const UPVOTE2 = createAction('[post] upvote2');
export const DOWNVOTE2 = createAction('[post] downvote2');

App.config.ts:

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { MetaReducer, provideState, provideStore } from '@ngrx/store';
import { posts1Reducer } from './posts1/posts1.reducer';
import { localStorageSyncReducer, postReducer2 } from './posts2/posts2.reducer';

const metaReducers : Array<MetaReducer<any,any>> = [localStorageSyncReducer]

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideStore({post2: postReducer2},{metaReducers}),
  ],
};

The state itself works fine, but nothing gets saved in the localstorage. I additionally tried other methods to provide the reducer:

  • As the ngrx documentation suggests leaving provideStore empty
provideStore(),
provideState('post2', postReducer2, {metaReducers});
  • Passing the reducer myslef
provideState({name:'post2', reducer: localStroageSyncReducer(postReducer2)})

I looked up for a lot of solutions but none of them applied to my case. Nothing seemed to work. What I am doing wrong?

0

There are 0 answers