Make custom store feature as singleton #4716
-
Which @ngrx/* package(s) are relevant/related to the feature request?signals InformationIt would be great if there was an ability to create a global(singleton) instance of a custom store feature,
Describe any alternatives/workarounds you're currently usingI tried the following to fulfill my requirement by just creating an instance of the
Thanks. I would be willing to submit a PR to fix this issue
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 12 replies
-
Hey @BarakDabach, I'd like to help but need more information. You want to have a feature which provide an instance of a global state, right? What about that: https://stackblitz.com/edit/github-ia7mxg23?file=src%2Fquiz.store.ts export const QuizStore = signalStore(
// features...
);
export function withQuizStore() {
return signalStoreFeature(
withProps(() => ({ quizStore: inject(QuizStore) }))
);
}
export const OtherStore = signalStore(
withQuizStore(),
withHooks((store) => ({
onInit() {
console.log(store.quizStore.title());
},
}))
); |
Beta Was this translation helpful? Give feedback.
-
I will write a concrete example of my desire @rainerhahnekamp |
Beta Was this translation helpful? Give feedback.
-
Lets say i have the following global state as a export type GlobalStateExample = {
globalProp1: string,
globalnum1: number,
globalnum2: number,
}
const initialState: GlobalStateExample = {
globalProp1:"global-string",
globalnum1:1,
globalnum2:2
}
//store feature
function withGlobalState() {
return signalStoreFeature(
{providedIn:'root'}, // just like in regular signal store - define that this feature is singletone
withState(initialState),
withComputed((store) =>({
computedString: computed(()=>`${store.globalProp1()}_${store.globalnum1()}`)
})
)
)
} and the following component export type ComponentState = {
loading: boolean
}
const initialState: ComponentState = {
loading: true
}
export const componentStore = signalStore(
withState(initialState),
withGlobalState(), // integrate the global store
withMethods((store) => ({
addOne(number:string){
var newGlobalValue = store.globalnum1() + number; // use the global property as part of the local store.
patchState(store,{globalnum1:newGlobalValue})
}
})),
) I am aware that this example domain is not the best - but i believe it gets the job done hope it clear what i want to achieve. @rainerhahnekamp - thank you for your support 💯💯💯 |
Beta Was this translation helpful? Give feedback.
-
I see what you mean. We have to split it because a |
Beta Was this translation helpful? Give feedback.
Well, in that case
I don't think it happens that often, that a local store wants to patch through data from the global store 1:1. What is your opinion on that?
Another alternative would be that your component is working with both global and local store.