Skip to content

Commit ebca86b

Browse files
michael-smallMichael
authored andcommitted
docs(ngrx/signals): mention of restructuring withComputed/withMethods for re-use
Issue: #4669
1 parent 734678e commit ebca86b

File tree

1 file changed

+32
-0
lines changed
  • projects/ngrx.io/content/guide/signals/signal-store

1 file changed

+32
-0
lines changed

projects/ngrx.io/content/guide/signals/signal-store/index.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,38 @@ export const BookSearchStore = signalStore(
309309

310310
</code-example>
311311

312+
<div class="alert is-helpful">
313+
314+
It may be necessary for a computed in a `withComputed` feature to need to reference another computed value,
315+
or a method in a `withMethods` feature to refer to another method. To do so, either:
316+
317+
(A) Create another `withComputed` feature or `withMethods` feature, or
318+
319+
(B) Break out the common piece with a helper `const`.
320+
321+
```ts
322+
export const BooksStore = signalStore(
323+
withState(initialState),
324+
// 👇 Accessing previously defined state signals and properties.
325+
withComputed(({ books, filter }) => ({
326+
booksCount: computed(() => books().length),
327+
sortDirection: computed(() => filter.order() === 'asc' ? 1 : -1),
328+
})),
329+
// 👇 (A) Also access previously defined computed properties (or functions).
330+
withComputed(({ books, sortDirection }) => {
331+
// 👇 (B) Define helper functions (or computeds).
332+
const sortBooks = (direction: number) =>
333+
books().toSorted((a, b) => direction * a.title.localeCompare(b.title));
334+
335+
return {
336+
sortedBooks: computed(() => sortBooks(sortDirection())),
337+
reversedBooks: computed(() => sortBooks(-1 * sortDirection())),
338+
};
339+
}),
340+
);
341+
```
342+
</div>
343+
312344
### Reactive Store Methods
313345

314346
In more complex scenarios, opting for RxJS to handle asynchronous side effects is advisable.

0 commit comments

Comments
 (0)