Phong6698
Phong6698

Reputation: 499

Reuse a computed signal in NGRX signal store

In NGRX signal store, I want to reuse the computed value in another computed value that is in withComputed.

For example:

export const ExampleStore = signalStore(
  withState(initialState),
  withComputed(store => ({
    property1: computed(() => store.example()),
    property2: computed(() => store.property1()),
  }))
);

store.property1() is no callable in computed

Upvotes: 2

Views: 623

Answers (1)

Phong6698
Phong6698

Reputation: 499

There are 2 patterns I know of:

Use a second withComputed

export const ExampleStore = signalStore(
  withState(initialState),
  withComputed(store => ({
    property1: computed(() => store.example()),
  })),
  withComputed(store => ({
    property2: computed(() => store.property1()),
  }))
);

In the same withComputed

export const ExampleStore = signalStore(
  withState(initialState),
  withComputed(store => {
    const property1 = computed(() => store.example());
    const property2 = computed(() => property1());
    
    return {property1, property2};
  })
);

Upvotes: 6

Related Questions