Reputation: 1074
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?
Upvotes: 1
Views: 1437
Reputation: 51
you can use selectSnapshot
selectSnapshot(StateName.SelectorName);
example
const dataInsdeStore = this.store.selectSnapshot(StateName.SelectorName);
if (!dataInsdeStore) {
this.store.dispatch(new FooActions.GetAll());
}
dataInsdeStore
return data, the store already has data, and you
don't need to call the APIdataInsdeStore
return null or empty, you need to call API because the state is emptyresource for selectSnapshot
Upvotes: 0
Reputation: 8773
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.
Upvotes: 1