mfellner / valtio-factory

Create and compose valtio state using the factory pattern.
https://codesandbox.io/s/valtio-factory-example-j7v2s
MIT License
40 stars 2 forks source link

How to define derived props in the initial state object? #4

Closed vforsh closed 1 year ago

vforsh commented 1 year ago

Hi,

In the current implementation, derived properties are defined using the .derived() method, separate from the initialState object. For example:

const initialState = {
    magicLevel: {
        points: 0,
        // TODO define derived properties here, near the "original" properties
    },
};

const storeFactory = createFactory(initialState)
    .derived({
        magicLevelStage: (state) => state.magicLevel.points * 10,
    })
    .actions(actions);

I find this approach inconvenient because I would prefer to have derived properties defined in the same place as the "original" properties, within the initialState object. This would make it easier to see the relationships between properties at a glance.

Is there any way to achieve this?

Thanks a lot for a great library! It's a really nice addition on top of the original Valtio.

mfellner commented 1 year ago

Thanks for the feedback! 😃 I'm afraid it's probably not feasible to do this with valtio-factory. The reason is that the regular "derive" util also works by "decorating" an existing store:

import { derive } from 'valtio/utils'

// create a base proxy
const state = proxy({
  count: 1,
})

// create a derived proxy
const derived = derive({
  doubled: (get) => get(state).count * 2,
})

// alternatively, attach derived properties to an existing proxy
derive(
  {
    tripled: (get) => get(state).count * 3,
  },
  {
    proxy: state,
  }
)

valtio-factory's pattern consciously separates features into chained methods for better composability. Maybe a different pattern would work better for your use case? There's also https://github.com/mfellner/valtio-inversify (highly experimental) which uses classes.

vforsh commented 1 year ago

Got it, thanks! Will definitely check valtio-inversify too.