platform icon indicating copy to clipboard operation
platform copied to clipboard

`@ngrx/signals`: Allow returning computation functions from `withComputed` callback

Open markostanimirovic opened this issue 7 months ago • 3 comments

Which @ngrx/* package(s) are relevant/related to the feature request?

signals

Information

Provide the ability to return computation functions from withComputed callback in addition to signals to reduce repetitive code in the most common use case:

const CounterStore = signalStore(
  withState({ count: 0 }),
  withComputed(({ count }) => ({
    doubleCount: () => count() * 2,
  })),
);

If the computed signal needs to be used before it's returned or if it has custom equal function, it's still necessary to explicitly use computed API:

const CounterStore = signalStore(
  withState({ count: 0 }),
  // 1: custom equal
  withComputed(({ count }) => ({
    doubleCount: computed(() => count() * 2, { equal: /* ... */ }),
  })),
  // 2: using computed signal before returning it:
  withComputed({ count }) => ({
    const doubleCount = computed(() => count() * 2);

    return {
      doubleCountPlus1: () => doubleCount() + 1,
      doubleCount,
    };
  })),
);

Describe any alternatives/workarounds you're currently using

No response

I would be willing to submit a PR to fix this issue

  • [ ] Yes
  • [ ] No

markostanimirovic avatar May 17 '25 21:05 markostanimirovic

I would gladly have a look at this in a few days, if nobody implemented it until then.

iliev-ilian avatar May 29 '25 20:05 iliev-ilian

@iliev-ilian Issues with the Core/Collaborators Work label will be handled by the NgRx team. If you're interested in contributing, you can search for issues that have the Accepting PRs label.

markostanimirovic avatar May 29 '25 20:05 markostanimirovic

In order to speed up the NgRx v20 release, I've taken the liberty of creating a PR for this one.

rainerhahnekamp avatar Jun 07 '25 23:06 rainerhahnekamp