Comments (15)
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.
from platform.
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).
from platform.
@gabrielguerrero, I think - and please correct me if I'm wrong - we are talking here about two different features.
- You need more feature functions and want to fix that by using
signalStoreFeature
because that's the closest thing at hand. So your usage ofsignalStoreFeature
is bound to a specificsignalStore
.
flowchart LR
signalStoreFeature --> Service --> signalStore
- I was speaking of providing a generic
signalStoreFeature
which needs to get features of an existingsignalStore
by not depending on it.
flowchart LR
ServiceImplementation --> signalStore
withFeatureFactory --> GenericService
withFeatureFactory --> ServiceImplementation
signalStoreFeature --> GenericService
I'd we need both but maybe not under the same name.
from platform.
you find a working and typed solution at https://stackblitz.com/edit/ngrx-signal-store-starter-z3q5i5?file=src%2Fmain.ts
Your withIncrement
will not get the store but an wrapper function which patches the state. By doing that we can decouple withIncrement
from the specific store and make it therefore reusable.
from platform.
@rainerhahnekamp I tried to implement again the withTabVisibility
feature, using withFeatureFactory
and I do not need internal types anymore 😍
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()),
}),
)
)
from platform.
@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;
}
from platform.
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.
from platform.
Having thought on this more, maybe this could be an overload of the signalStoreFeature like
signalStore(
withMethods(() => {
const httpClient = inject(HttpClient);
return {
load() {
return httpClient.get<Person[]>('someUrl');
},
};
}),
signalStoreFeature((store) => withEntityVersioner(() => store.load())),
);
from platform.
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.
from platform.
Is this proposal also intended to enable other signalStoreFeatures to manipulate the state of a store?
Something like:
const counterStore = signalStore(
{ providedIn: 'root' },
withState(intitialState),
witSharedState((store) => withIncrement<counter>('items', store))
);
function withIncrement<Entity extends object>(
key: keyof Entity,
sharedStoreIn: StateSignal<Entity>
) {
return signalStoreFeature(
withMethods(() => {
const sharedStore = sharedStoreIn as any; //How to type the store?
return {
withIncrement() {
patchState(sharedStore, { [key]: sharedStore[key]() + 1 });
},
};
})
);
}
Even if it is not intended, could someone help me to type out that use case?
https://stackblitz.com/edit/ngrx-signal-store-starter-23tsna?file=src%2Fmain.ts
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()".
from platform.
@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
from platform.
@rainerhahnekamp in your last example, it seems weird to move the updaterFn
out of the custom feature. I like the withFeatureFactory
, but I'd rather use it like this:
https://stackblitz.com/edit/ngrx-signal-store-starter-qedtku?file=src%2Fmain.ts
But a type SignalStoreFeatureStore
would be needed (I am not sure about the naming of this type 😅)
from platform.
Hi @GuillaumeNury, yeah that's much better.
In the end, it is the old story about getting access to the internal types, right?
from platform.
@GuillaumeNury, @Donnerstagnacht: I've updated my version. Turned out that the only type we really need is SignalState
and that one is public.
So we can use the version of @GuillaumeNury and not violate the encapsulation.
from platform.
@rainerhahnekamp kind of. But with SignalState
+ 'withFeatureFactory' we can keep internals hidden 🎉
I changed the generic of withIncrement
to allow the state to have non-numeric properties : https://stackblitz.com/edit/ngrx-signal-store-starter-pozgde?file=src%2Fmain.ts
The result looks wonderful! I hope to see this in v18.X 😁
from platform.
Related Issues (20)
- computed not re-calculating if signal is inside function HOT 1
- [Bug] @ngrx/signals: DeepSignal is not exported HOT 3
- UpdateStr and UpdateNum are not export in index HOT 2
- Document ESLint v9 support
- Add v18 migration guide
- Add eslint rule for signalState and withState
- [18.0.0-rc.0] Failed to load config "plugin:@ngrx/recommended-requiring-type-checking" HOT 8
- bug(eslint-plugin): signals configuration
- tapResponse error parameter response returns an error observable not the error. HOT 1
- Rename `signals` to `computed` when defining custom features with input for consistency
- `@ngrx/signals/entity`: Replace `idKey` with `selectId`
- `@ngrx/signals/entity`: Introduce `entityConfig` function
- `@ngrx/signals` v18.0.0 Release HOT 10
- 17.2.0 -> 18.0.0 Schematics wreak havoc in files HOT 10
- RFC: Introduce `watch` function to `@ngrx/signals` HOT 34
- RFC: Limit direct state updates outside a SignalStore HOT 25
- Migration for concatLatestFrom produces garbled code on ng update from 17 to 18 HOT 2
- @ngrx/[email protected] dependency check fails with ng-recaptcha@latest HOT 1
- RFC: Add a reactivity layer to signalStore (withEvents, withReducer, and withEffects) HOT 29
- false positive for rule @ngrx/no-multiple-actions-in-effects HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from platform.