-
-
Notifications
You must be signed in to change notification settings - Fork 2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
RFC: signalStoreFeature
and access to Store
#4340
Comments
@rainerhahnekamp I had a need for this in an app, and I gave it a go at trying to implement it, I got it working, and then just noticed you had a version in stackblitz, my version has a few improvements like it keeps the wrapped feature input type in case you need it as well import { SignalStoreFeature } from '@ngrx/signals';
import type {
SignalStoreFeatureResult,
SignalStoreSlices,
} from '@ngrx/signals/src/signal-store-models';
import type { StateSignal } from '@ngrx/signals/src/state-signal';
import { Prettify } from '@ngrx/signals/src/ts-helpers';
export function withFeatureFactory<
Input extends SignalStoreFeatureResult,
Feature extends SignalStoreFeature<any, any>,
>(
featureFactory: (
store: Prettify<
SignalStoreSlices<Input['state']> &
Input['signals'] &
Input['methods'] &
StateSignal<Prettify<Input['state']>>
>,
) => Feature,
): SignalStoreFeature<
Input & (Feature extends SignalStoreFeature<infer In, any> ? In : never),
Feature extends SignalStoreFeature<any, infer Out> ? Out : never
> {
return ((store: any) => {
const { slices, methods, signals, hooks, ...rest } = store;
return featureFactory({
...slices,
...signals,
...methods,
...rest,
} as Prettify<
SignalStoreSlices<Input['state']> &
Input['signals'] &
Input['methods'] &
StateSignal<Prettify<Input['state']>>
>)(store);
}) as Feature;
} |
Thanks, I never used it honstly. Was just a quick prototype. In our extensions we still depend on the non-public types. This feature would improve the situation, but only if it lands in the core (also depends on internal types). |
That's a good point. I also use non-public types in a few places, but this is mainly because I need to allow methods to use things from the store. If this were part of the core, it would reduce the need to expose those non-public types. |
Having thought on this more, maybe this could be an overload of the signalStoreFeature like
|
I would love to write: signalStore(
withMethods(() => {
const httpClient = inject(HttpClient);
return {
load() {
return httpClient.get<Person[]>('someUrl');
},
};
}),
withEntityVersioner((store) => store.load()),
); But as I asked in #4272, it requires to expose more types to the public API. |
@gabrielguerrero, I think - and please correct me if I'm wrong - we are talking here about two different features.
flowchart LR
signalStoreFeature --> Service --> signalStore
flowchart LR
ServiceImplementation --> signalStore
withFeatureFactory --> GenericService
withFeatureFactory --> ServiceImplementation
signalStoreFeature --> GenericService
I'd we need both but maybe not under the same name. |
Hey @rainerhahnekamp, I was indeed referring to having the withFeatureFactory be just an overloaded in signalStoreFeature, my reasoning was that the names are similar and I was not sure about the name withFeatureFactory when its main goal is just to give access to the store to another store feature, I don't want people to think they can be use to create store features, that's signalStoreFeature job, which is where I got the idea of maybe making it part signalStoreFeature, an overloaded version that receives factory function with the store as param. I'm just brainstorming, really; I'm not really sure it is a good idea; maybe we just need a different name for withFeatureFactory. |
Is this proposal also intended to enable other signalStoreFeatures to manipulate the state of a store? Something like:
Even if it is not intended, could someone help me to type out that use case? Probably, it could also be an idea to let developers choose if they want to share store elements and offering a system like "shareState()", "shareMethods(), "shareStore()". |
you find a working and typed solution at https://stackblitz.com/edit/ngrx-signal-store-starter-z3q5i5?file=src%2Fmain.ts Your |
@Donnerstagnacht you can also do it with already available feature store Input condition (as documented here) https://stackblitz.com/edit/ngrx-signal-store-starter-rlktqe?file=src%2Fmain.ts |
@rainerhahnekamp in your last example, it seems weird to move the https://stackblitz.com/edit/ngrx-signal-store-starter-qedtku?file=src%2Fmain.ts But a type |
Hi @GuillaumeNury, yeah that's much better. In the end, it is the old story about getting access to the internal types, right? |
@GuillaumeNury, @Donnerstagnacht: I've updated my version. Turned out that the only type we really need is So we can use the version of @GuillaumeNury and not violate the encapsulation. |
@rainerhahnekamp kind of. But with I changed the generic of The result looks wonderful! I hope to see this in v18.X 😁 |
@rainerhahnekamp I tried to implement again the https://stackblitz.com/edit/ngrx-signal-store-starter-dmybgr?file=src%2Fmain.ts The only change is going from: signalStore(
withTabVisibility({
onVisible: (store) => store.loadOpportunity(store.opportunityId()),
})) to: signalStore(
withFeatureFactory((store) =>
withTabVisibility({
onVisible: () => store.loadOpportunity(store.opportunityId()),
}),
)
) |
There is no need for a separate As described in https://ngrx.io/guide/signals/signal-store/custom-store-features#example-4-defining-computed-props-and-methods-as-input, the shown example can easily be solved with the existing functionalities: interface Person {
firstname: string;
lastname: string;
}
function withEntityVersioner<Entity>() {
return signalStoreFeature(
{ methods: type<{ loader: () => Observable<Entity[]> }>() }, // <-- that's the key (and typesafe)
withState({ version: 1, entities: new Array<Entity>() }),
withMethods((store) => {
return {
update: rxMethod<unknown>(
pipe(
switchMap(() => store.loader()),
filter((entities) => entities !== store.entities()),
tap((entities) =>
patchState(store, (value) => ({
entities,
version: value.version + 1,
}))
)
)
),
};
}),
withHooks((store) => ({ onInit: () => store.update(interval(1000)) }))
);
}
signalStore(
withMethods(() => {
const httpClient = inject(HttpClient);
return {
loader() {
return httpClient.get<Person[]>('someUrl');
},
};
}),
withEntityVersioner() // does not compile
); |
@rainerhahnekamp it is indeed possible to use what is currently available, but the DX does not feel good. What if I want multiple IMHO, signalStore(
withFeatureFactory(
(store, httpClient = inject(HttpClient)) =>
withEntityVersioner({
loader: () => httpClient.get<Person[]>('someUrl')
})
)
); |
@GuillaumeNury, I understand. The question is whether that use case happens so often that it verifies a new feature. I could update my example and re-open this issue. What's your opinion on that? |
For more advanced features, I find the state/method requirements not very ergonomic. I think that exposing a |
The Take a look at the implementation of |
Hey @markostanimirovic there is a use case that I struggle a bit to find a nice solution that withFeatureFactory would help, I been asked by users of ngrx-traits export function withEntitiesLocalSort<
Entity,
Collection extends string,
>(configFactory: (store: SignalStore<Input) => {
defaultSort: Sort<Entity>;
entity: Entity;
collection: Collection;
idKey?: EntityIdKey<Entity>;
}): SignalStoreFeature<Input, any>{
const config = configFactory(store) // need the store
} I keep finding the best way is like you do in withMethods which is pretty similar to what withFeatureFactory does (maybe a better name for it could be withStore ) but it uses internal stuff. The main reason the solution you did in the previous comment withTabVisibility would not work in this case is that I will need to execute the configFactory inside each withState, withMethods or withHooks that is inside the feature which is not ideal, or create a getConfig withMethod that evaluates the configFactory and exposes a new method. Another problem is that withState has a factory version but doesn't receive the store (maybe that could be a feature request on its own). I tried a few other ways where I tried to avoid using internals, but all ended up more complicated than what withMethods and withFeatureFactory do to transform the InternalStore to SignaSource. I think withFeatureFactory(or withStore :) ) or something similar will be a nice way to hide the internals of transforming the inner store to signalsource. |
Thanks for the info, Gabriel! We're considering introducing another base feature - Btw, it's possible to use symbols for state/computed/method names. In the case of const SORT_CONFIG = Symbol('SORT_CONFIG');
export function withEntitiesLocalSort<Input extends SignalStoreFeatureResult>(/* ... */) {
return signalStoreFeature(
type<Input>(),
withMethods((store) => ({
[SORT_CONFIG]: () => configFactory(store),
})),
// ...
);
} |
Hey @markostanimirovic, that withProps sounds super interesting :), you know, sometimes I think an experimental subpackage could be useful to get feedback from new ideas. And thanks I did not knew symbol props were working now thats great I will try |
Which @ngrx/* package(s) are relevant/related to the feature request?
signals
Information
This is a proposal for connector function which connects a signalStore to a feature and provides the feature access to store-specific elements.
A StackBlitz example is available here: https://stackblitz.com/edit/ngrx-signal-store-starter-wkuxdh
Sometimes, our Signal Store Features require features from the store they should be plugged in. Since features should be re-usable, direct coupling is impossible.
Following use case. A feature requires access to a loading function which is defined in
withMethods
of the store.We have the following feature
And a store which wants to use it:
The proposed feature is about a function
withFeatureFactory
which connects an autonomous feature to a specific store.The type of
withFeatureFactory
would look like this:This feature would be helpful in the discussion #4338.
Although, it is different use case, it is very similar to the suggestion of @gabrielguerrero in #4314 (comment)
Describe any alternatives/workarounds you're currently using
The alternative is that the
load
function in the example would come from a service which thesignalStoreFeature
has to inject.I would be willing to submit a PR to fix this issue
The text was updated successfully, but these errors were encountered: