0

So, I'm trying to use NGXS for the first time, and I noticed that when I add the following code in Angular's ngOnInit() function, it always fetches the API:

this.store.dispatch(new FooActions.GetAll());

This might seem like a stupid question but, shouldn't NGXS check if the store already has data and use that instead of calling the API? Or is it not part of the feature? And should I just do the checking manually each time I'm dispatching an action for getting data from the server?

Newsha Nik
  • 806
  • 2
  • 12
  • 29
Jed
  • 1,054
  • 1
  • 15
  • 34

2 Answers2

1

So, there are two things here which will be done to reduce the API call. When you do an API call, browser fetches the data and if cache is enabled it keeps the data in cache.

Now, when you use state management, you need to store the API data into the store every time you refresh or reload the app as it is not a persistent storage for your data.

This means, before calling an API you should check whether you have data in store or not. If you have data, just fetch it from the store and follow the same application flow else hit the API and get fresh data and save it in the store.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
  • Yes I understand that it doesn't persist when you reload. But when you're just navigating through Angular's routes, I thought that the idea was just use the store and just fetch from API when the store's empty. I mean automatically at least. – Jed Nov 16 '21 at 08:57
  • It can do auto if you create that functionality. You can create a service that can check before every API call or add an intercept service for evry api call whether store has that data or not. – Apoorva Chikara Nov 16 '21 at 09:55
0

you can use selectSnapshot

selectSnapshot(StateName.SelectorName);

example

const dataInsdeStore = this.store.selectSnapshot(StateName.SelectorName);

if (!dataInsdeStore) {

   this.store.dispatch(new FooActions.GetAll());

}
  1. if dataInsdeStore return data, the store already has data, and you don't need to call the API
  2. if dataInsdeStore return null or empty, you need to call API because the state is empty

resource for selectSnapshot

ngxs Docs