Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
    chrismarx
    @chrismarx_twitter
    Hi, I'm using persistState with localForage, but some of my entities have functions in some of the properties, and these can't be persisted. I can remove the offending functions in the preStorageUpdate hook, but because Akita pushes the entire contents of the storeState on every update, entities that were loaded initially still have their functions in them. If I make changes to the stores with functions in the properties, then the preStorageUpdate works just fine, since in that case the stripped state is stored. Any ideas how to make this work?
    Pascal Graf
    @Spinnenzunge_gitlab
    does the selectAll() query of an entity store always return an observable that emits an array? I am wondering if it is possible that selectAll returns undefined or null. I am asking because I need to differentiate empty and not yet loaded
    I could do it with an UI property but I just want to know weather or not it is possible with the selectAll query. Setting my entities in initial state still returns an empty array if i subscribe to selectAll()
    8 replies
    Antonio Jorge Bodoc
    @ajbodoc
    Hi,
    I have tried implementing Akita, along with firebase, using a tutorial from https://netbasal.com/akita-and-firebase-a-match-made-in-angular-heaven-4a47ff889208
    But I'm having trouble getting the QueryService to work, it doesn't return an empty query, even though it contains documents.
    The code:

    @Injectable({ providedIn: 'root' })
    export class ActividadService implements OnDestroy {

    //actividades: AngularFirestoreCollection<Actividad>;
    private suscription: Subscription;

    actividadesCollection: AngularFirestoreCollection;

    constructor(private afs: AngularFirestore, private fs: FirestoreService, private actividadStore: ActividadStore) {
    this.actividadesCollection = afs.collection('actividades');
    this.fetch();
    }

    fetch() {
    this.actividadesCollection.valueChanges().subscribe((actividades: Actividad[]) => {
    this.actividadStore.set(actividades);
    console.log('fetch: ', actividades);
    });
    }

    in use:ngOnInit(): void {
    this.actividades = this.actividadQuery.getAll();
    console.log('actividades: ', this.actividades);
    if (this.actividades) {
    this.actividad = this.actividades[0];
    this.dataSource = new MatTableDataSource<Actividad>(this.actividades);
    this.dataSource.paginator = this.paginator;
    if (this.sort) {
    this.sort.active = 'id';
    this.sort.direction = 'desc';
    }
    this.dataSource.sort = this.sort;
    console.log('actividades: ', this.actividades.length);
    }
    }
    naveen554
    @naveen554
    how can we add one row without id to akita store, can we create tempid or any another alternate
    Erik
    @Everduin94
    Is there a way to programmatically export state. Similar to the export button in redux dev tools when using Akita?
    Jam-e-dev
    @jam-e-dev

    Hi, I'm having a recent issue with Akita and wondering if anyone has ran into something similar.

    I'm using an EntityUIStore, storing a complex object. When I attempt to upsert on this store, I get this error: ERROR TypeError: can't redefine non-configurable property 0
    This error is being raised in Akita's deepFreeze function.

    One of the fields of the complex object is an object adhering to an interface with a single index accessor signature.

    The error is not raised if I manually call Object.freeze on my object before calling the Upsert.

    1. Is manually calling freeze before upsert going to cause me issues?
    2. Why is this error being raised? The object was constructed from JSON.parse so I don't understand why the store would suddenly start failing once I introduced this complex object type
    Jam-e-dev
    @jam-e-dev
    ^ If anyone else runs into this, the issue was due to:
    1. Akita freezes objects by default when not run in production mode
    2. My complex object contained a typed array
    3. JS typed arrays can not be frozen.
    Changing to production mode resolved my problem
    Jefferson Nilo
    @jeffyzxc

    @jeffyzxc
    Hi i am having a problem with PersistStateSelectFn

    I followed the docs but it persists all my state

    let selectArticleEditorEntities:PersistStateSelectFn<ArticleEditorState> = (state) => (
      { entities: state.entities, ids: state.ids}
    );
    selectArticleEditorEntities.storeName = 'article-editor';

    i am also getting type error on my variable

    Type '(state: ArticleEditorState) => { entities: HashMap<ArticleEditorModel>; ids: any[]; }' is not assignable to type 'PersistStateSelectFn<ArticleEditorState>'.
      Property 'storeName' is missing in type '(state: ArticleEditorState) => { entities: HashMap<ArticleEditorModel>; ids: any[]; }' but required in type '{ storeName: string; }'.ts(2322)
    persistState.d.ts(12, 5): 'storeName' is declared here

    am i using it wrong?

    1 reply
    madhankumar
    @madhanhere

    Hi all, I need a help here. I doing unit test for my angular project. I'm having a component. Here, I need to write case, to make my cart query to return an object. How to do that?

    class CartComponent implements OnInit {
    
        showWarning$: Observable<boolean>;
    
        constructor(
            cartQuery: CartQuery,
            availabilityService: AvailabilityService
        ) {
        }
    
        ngOnInit() {
            showWarning$ = cartQuery.lastAddedItem$.pipe(
                switchMap(item => availabilityService.check(item))
            );
        }
    }
    
    interface CartState {
        items: Item[]
    }
    
    class CartQuery extends Query<CartState> {
        lastAddedItem$ = this.select(state => state.items[items.length - 1]);
    }

    My spec snippet:

    describe('CartComponent', () => {
      let component: CartComponent;
      let cartQuery: CartQuery;
      let availabilityService: AvailabilityService;
      let fixture: ComponentFixture<CartComponent>;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
          providers: [
            CartQuery,
            AvailabilityService,
          ],
          declarations: [
            CartComponent,
          ],
        }).compileComponents();
      });
    
      beforeEach(() => {
        fixture = TestBed.createComponent(CartComponent);
        component = fixture.componentInstance;
        availabilityService = TestBed.inject(AvailabilityService);
        cartQuery = TestBed.get(CartQuery);
      });
    
      it('component created', () => {
        expect(component).toBeTruthy();
      });
    
      it('check cart item when it get added', done => {
        cartQuery.select.and.returnValue(of([{id: 13324, name: 'cycle', price: 23245}]))
        fixture.detectChanges();
    
        component.showWarning$.subscribe({
           next: val => {
             expect(val).toBe(false)
           },
           complete: () => done()
         });
      });
    
    });

    I'm getting the error: Property 'and' does not exist on type '

    1 reply
    Pascal Graf
    @Spinnenzunge_gitlab
    I have a problem when using entity UI state together with a persisted entity state. It seems like my entity UI state (which i do not want to persist) is not created if my existing entity state is loaded from storage.
    Chirag Maheshwari
    @chiragmaheshwari
    Hello everyone, using history plugin, can we get all the values stored in history for a particular property I am keeping watch on?
    Pascal Graf
    @Spinnenzunge_gitlab
    @NetanelBasal How is the storage initialised from storage to memory when using persistStorage? I have a problem that my EntityUI State (not persisted) is not initialised with defaults for all entities for my entity state that is loaded from the persistence
    Tom Grant
    @granttw

    Hello,

    I am new to Akita and so far I am loving it. I am coming from using NGRX for a while and I have to say that Akita's approach resonates with me in a way that NGRX does not.

    I do have some feedback though on the documentation. For the most part, I would say that the documentation is good. But there is room for improvement. I find that the samples leave out really important information, usually leading to confusion and time wasted.

    Topic: NG Entity Server
    Page: https://datorama.github.io/akita/docs/angular/entity-service

    Issue:
    The sample given in the "Getting Started" section titled posts.component.ts shows:

    update(id) {
        this.postsService.update(id, { title: 'New title' }).subscribe({
          error: (error) => {
            this.error = error;
          }
        });
      }

    I noted that the second argument was a partial object. Interesting, does Akita do some magic here and either create a full object for me or automatically determine that I need to use a patch? I don't see any mention of specifying PATCH anywhere in this sample so it must take care of that.

    So I proceed to use it in my code. My result is a 404 error saying it was not found. Hmmm ... what is going on?

    So I inspect the HTTP request and the body only contains the partial object. I go to the source code for the update method and see that it just passes whatever I give it directly through to the http request.

    Well, that isn't going to work. Is the sample wrong? Can you not send in partial objects? I am losing trust in the documentation at this point.

    This sends me down a rabbit hole that I will not go into detail about. Needless to say, I spend more time trying to figure out if the documentation is correct or incorrect. I finally get my answer. I started looking through the source code for the sample app and note that it configures in app.module.ts that http method PUT gets mapped to PATCH. That was significant info that should have been stated in the documentation for NG Entity Server. A one line statement: The above code requires you to configure that PUT request get converted to PATCH requests. As a bonus, show the following code in the app.module.ts sample shown earlier on this page.

    {
          provide: NG_ENTITY_SERVICE_CONFIG,
          useFactory: function () {
            return {
              baseUrl: 'https://jsonplaceholder.typicode.com',
              httpMethods: {
                PUT: HttpMethod.PATCH,
              },
            } as NgEntityServiceGlobalConfig;
          },
          deps: [],
        }

    I spent the weekend trying to figure this out and I wanted to share in hopes of saving someone else from the amount of time I spent.

    Trần Hữu Long
    @uranussolutions
    image.png
    Hi everybody. I'm using Akita's PaginatorPlugin but there's a no save cache error when switching between pages. I follow the example on github. Someone please help me. thank you
    ONeia
    @Oneia
    Hi everybody. What do you think about making all services in angular app 'forRoot'? Even the service is using in one particular module
    Miloš Lapiš
    @mlc-mlapis
    @Oneia Hmm, you probably want to minimize the size of the app's main bundle so you want to move them to the lazy loaded modules?
    ONeia
    @Oneia
    @mlc-mlapis yes, but does it cost? Size will be decreased for a very small
    also Akita CLI creates 'inRoot' by default
    Anton Shvets
    @antshvets_gitlab

    Hi everybody. What do you think about making all services in angular app 'forRoot'? Even the service is using in one particular module

    I amused. 'forRoot' became the only thing a long time ago. Or 'forRoot' or component scoped providers. In modules it is senseless.

    Miloš Lapiš
    @mlc-mlapis
    @Oneia It depends on the application size, of course. But there is also another factor. When you ignore this and then later, you would like to implement it, it can be a lot of work, so I recommend keeping the app's structure optimized from the beginning = keeping the size and code of the main eagerly loaded bundle as lower as possible.
    BosH
    @BosH9
    Hello everyone, I'm new to Akita .
    Is there any sample application built with Nx angular monorepo with Akita?
    BosH
    @BosH9
    @pavankjadda bro can you please help me on this?
    Pavan K Jadda
    @pavankjadda
    Not sure what you are expecting from me. But you can look at this example https://engineering.datorama.com/building-a-shopping-cart-in-angular-using-akita-c41f6a6f7255
    Diogo Marcelo
    @shindiogo_gitlab
    Hi everyone, where i can find changelog with last releases?
    lukonik
    @lukonik
    Hi Everyone I have complex class type ( with properties and methods ), which can't be converted into the plain object. is there any solution to handle this kind of objects into the Akita ?
    Jason Warner
    @griffajay_twitter
    Hi- I'm having issues unit testing and mocking my query provider in Angular 10 using Jest. I've attempted to follow the Akita Angular Unit Test documentation but get an error property 'and' does not exist on type '(id: any) => package' when calling myQueryService.getEntity.and.returnValue. I'm assuming the documentation is using Jasmine so I've also attempted jest.spyOn(myQueryService, 'getEntity').mockReturnValue(mockReturnValue) but the value is never mocked.
    Jason Warner
    @griffajay_twitter
    I've successfully mocked other service providers (non-Akita) so not sure what I'm doing wrong.
    Jason Warner
    @griffajay_twitter
    Think I figured out the issue, but still need to wrap my head around the context. I was providing the query service in multiply locations, (1) in the @Component providers array and (2) in the constructor as a private service. The tests and mocks started working once I commented the @Component provider. Don't fully know why this worked, but guessing my spy wasn't finding or using the correct dependency injection token.
    Jordan
    @kingjordan
    hello, I'm looking for some sample code for dispatching actions/effects as a result of a router change. I'm trying to keep my router state as the "single source of truth" for app state. specifically best practice and common pitfalls. I am leaning towards using resolvers to trigger the effects.
    Matt Jones
    @mdonjones
    Hey all - I'm updating a project that uses Akita 3.X as well as the AkitaNgFormsManager plugin. I know the plugin has been deprecated in favour of the ngneat one, but is still compatible with latest versions of Akita?
    ONeia
    @Oneia

    Hi. Does anybody know why the NgEntityServiceLoader doesn't work correctly for the get observable?

    for example:

    (myLoader.get$ | async)

    the code above doesn't return true, it just returns false when the fetch is over and it only happens with the get$

    Mathieu Renda
    @rendmath
    Hi everyone. Can you confirm that resetStores() will only actually reset stores that have been loaded since the startup of the application? The only way to completely reset the storage of all stores, irrespective of whether they have been loaded or not, seems to be to remove the key from local/sessionStorage ourselves.
    Mathieu Renda
    @rendmath
    Actually even this doesn't seem to work, I do both resetStores and localStorage.removeItem() and some stores still contain data.
    Landon Buttars
    @landonbuttars
    Hey gents, I'm trying to test a component that uses the RouterQuery. What is the right approach to get this working? I'm using jest.
    Mohendran
    @Mohendran
    Hi...
    I'm currently calling the same API many times, and it cannot be cancelled. I want to update the last response from the api to the store. Does anyone have an idea on how to implement that with rxjs or any akita functions?
    jorugit
    @jorugit
    Best Practices: How can i store entities in one store to save datatraffic but use different subsets in different components? (for example two searches at same time, results has overlaps)
    jaytonic
    @jaytonic

    Hi! Just a question, I'm trying to setup my angular 12 project with akita, and especially akita-ng-fire. I've started by using the classes here: https://github.com/dappsnation/akita-ng-fire/tree/v6/src/app/auth/%2Bstate

    On the AuthQuery, with the code of the github, I've the following warning:
    No suitable injection token for parameter 'store' of class 'AuthQuery'.
    Consider using the @Inject decorator to specify an injection token.

    Any idea how to fix this?

    jaytonic
    @jaytonic

    And my second question: As soon I'm trying to query something from my authQuery, I get an error:

    Error: The target entry-point "akita-ng-fire" has missing dependencies:

    • @datorama/akita-ng-router-store

    Even I don't want to use the akita-ng-router-store. Is it possible to use the akita-ng-fire auth without using the akita-ng-router-store?

    Srivatsa
    @ivatsa
    Is Akita persistState() specific to angular? Can I use in plain JS?
    Andrea Ferrandi
    @aferrandi
    Hi.
    The application I'm working with gets an error when it calls resetStores() during the logout.
    In the getEntity() function "entities" is undefined when indirectly called by dispatch() in watchTransaction(), when closing the resetStores() transaction.
    The version of Akita is 4.22, but it happens also in 5.3.
    Do i do something wrong somewhere?
    Bryan Neva
    @bryanneva
    I noticed that the master branch of Akita depends on RxJS 6.6.7. Is there a release that tracks RxJS v7? I have a lot of type conflicts using operators from rxjs/operators against akita stores and I'd prefer to use rxjs v7 if possible.
    1 reply
    Sameera Perera
    @sameera
    Hi
    We are evaluating moving to Akita from NgRx. So, I have a ton of noob questions. First is, where can I find more info on the setLoading method? Docs page for it (https://datorama.github.io/akita/docs/store/#setloading) doesn't give much info. And there aren't any hits on Google for as to why I would want to call it. I see it used everywhere; on loading data on to the store. But why is this needed? What's the consequence of not calling it?
    4 replies
    Michael Marcuccio
    @michaelmarcuccio

    is there a built in way to partition persisted state on a per user basis? if user is x, load the persisted state from user x.

    const storage = persistState({
      include: [
        (storeName) => storeName === 'test'
      ],
      preStorageUpdate(storeName, state) {
        return { userId: **loggedInUserId, state };
      },
      preStoreUpdate(storeName, state) {
        if(state.userId === **loggedInUserId)
        return state.state;
      }
    });
    const providers: StaticProvider[] = [
      { provide: 'persistStorage', useValue: storage }
    ];

    Above is basically what I am looking for, but requires the persisted state to be process after user login. This code is in main.ts which is a bit before that occurs.