Home > OS >  With NGXS, what is the recommended way of calling the backend before calling the local state
With NGXS, what is the recommended way of calling the backend before calling the local state

Time:04-08

I'm starting a new angular app and doing the setup for the team. One thing I'm wondering: where do you put the logic to access the backend?

In my (first) case, about the accounts/auth, I need to store, username/email/accessToken, and typically every time a token is received, I want to start a timer to refresh the access token before it expires.

After some research, I see that some people recommend having the API call in the action handler in my State. But honestly, it feels a bit like mixing different responsibility, and since this will be for quite a big application, I'm a bit concerned that we end up with a state class that will be huge. Also in this case, when I receive my token, I need to have a timer to refresh it. I was more seing NGXS as a library to apply mutation on my state and propagate changes, not something should be responsible of having such logic(I'm maybe wrong?)

So, is there a recommended way of doing this with NGXS? Should we call a service that does the API call and then dispatch an action?

CodePudding user response:

I think the NGXS with Facade design pattern is helpful in this case, which can:

  • Improve the readability and usability of a software library by masking interaction with more complex components behind a single (and often simplified) API;
  • Provide a context-specific interface to more generic functionality (complete with context-specific input validation);
  • Serve as a launching point for a broader refactor of monolithic or tightly-coupled systems in favor of more loosely-coupled code.

You can read more about NGXS Facade here:

https://medium.com/ngxs/ngxs-facade-3aa90c41497b

  • Related