ngrx / platform

Reactive State for Angular
https://ngrx.io
Other
8.03k stars 1.97k forks source link

use 'inject' in reducer #3749

Closed jiangyh1024 closed 1 year ago

jiangyh1024 commented 1 year ago

Which @ngrx/* package(s) are relevant/related to the feature request?

store

Information

I'm using ng14.

when initializing the state, I wanna retrieve the data from localestorage which I encapsulated in a service called StorageService

image

I tried using

const storageService = inject(StorageService) ---> inject method is provided by Ng14

but it didn't work

Describe any alternatives/workarounds you're currently using

image

this works, but it seems that is requires that the service has no other dependencies, otherwise we should specify deps

I would be willing to submit a PR to fix this issue

Armenvardanyan95 commented 1 year ago

Reducers are meant to be pure functions and are no place for injecting dependencies. You want to use an effect that works on app initialization (you can use ngrxOnInitEffects), get the data from localStorage inside that effect, then dispatch an action that hydrates the state with the data retrieved from localStorage. The reducer will handle that action like any other. I am positive we would never be allowed to use inject in reducers - and that is a good thing!

P.S. Never use localStorage directly in a reducer too, it breaks the function being a pure one. Accessing localStorage is a side effect and belongs in Effects

jiangyh1024 commented 1 year ago

oh ok. Thx for the explanation.

Armenvardanyan95 commented 1 year ago

@jiangyh1024 you're welcome!