NgRx get data from api but not storing it to state

49 views Asked by At

I am having problem in understanding one basic concept in ngrx implementation. One example is, I need some data to get from api to validate some information in my component but I may not need it after the validation is done. So I don’t want to store it in state as it will unnecessarily make state heavy . In this scenario if I use effect, without updating state, how can I get it my component.

Is it a good practice, in the above scenario, I can directly call service without using effect. Or there are some better implementation approach,

I don’t have any answer for this. I didn’t get any reference in the web for this situation.

2

There are 2 answers

0
James Moore On

You could use your service directly in your component. Or to keep your component thin you could instead create an action for what ever event is occurring when you go to validate the data in your component. Maybe that data your trying to validate should be in state.

  1. You enter in some data, it gets stored in the store.
  2. You click a button and a unique event dispatches "Special Data Submitted" (name it like an event not a command)
  3. You then create an effect that listening for that action validateSpecialData$. (name it like a function)
  4. validateSpecialData$ grabs the data your trying to validate from state, calls your api endpoint. If its valid, return action SpecialDataSubmittedValidatedSuccess, or if it fails SpecialDataSubmittedFailure. (Look up good action naming)
  5. On Success your reducer would toggle another piece of state that says whether or not the data entered is valid or not and you can use that in your component or another component.

Just an idea

0
Geo242 On

You don't need to use NgRx to manage every operation in your application. What you are describing is transient state that doesn't really need to touch NgRx at all.

The team at NgRx realized that there are situations like this all the time and developed the @ngrx/component-store library just for this type of use case (when you need a state that only lives as long as your component).

I think you will find this works better for what you are doing. However, there is nothing wrong with just creating a simple service of your own to handle this as well. If you go that route, just don't inject it into "root".