Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFC] Derived state in model #159

Open
kyleslight opened this issue May 18, 2020 · 1 comment
Open

[RFC] Derived state in model #159

kyleslight opened this issue May 18, 2020 · 1 comment
Labels

Comments

@kyleslight
Copy link
Collaborator

kyleslight commented May 18, 2020

Sometimes we have one state and its value will be changed if and only if another state is changed. Nowadays we have to update their states manually in actions, for instance:

{
  state: {
    num: 3,
    sqauredNum: 9
  },
  actions: {
    setNum: num => {
       return state => {
           state.num = num
           state.sqauredNum = num * num
       }
    }
  }
}

Is there a way to manage only core states and make the derived states (like sqauredNum) be re-calculated automatically (like Selectors in https://recoiljs.org/docs/introduction/core-concepts)

const defaultFunc = () => {}

{
  state: {
     num: 3,
     sqauredNum: ({ num }) => num * num // calculated state
     func: defaultFunc // function handler
  }
}

...

const App = () => {
  const [{ sqauredNum }] = useStore('xxx')
  // use sqauredNum
}
@kyleslight kyleslight added the ✨Feature Request New feature or request label May 18, 2020
@kyleslight kyleslight changed the title [request] Can we have derived state in model [RFC] Derived state in model May 18, 2020
@kyleslight
Copy link
Collaborator Author

Test cases:

// case 1
export const A = {
  state: {
    a: 1,
    c: ({ a, b }) => a + b,
    b: ({ a }) => a + 1
  }
}

// a = 1
// assert(b === 2)
// assert(c === 3)


// case 2
export const B = {
  state: {
    a: 1,
    b: ({ c }) => c + 1,
    c: ({ b }) => b + 1
  }
}

// a = 1
// throw Error('circular dependency in calculated state')
  • calculated state params must be deconstructed
  • calc dependency can be expressed as
{
  a: 1,
  b: ({a}) => a + 1,
  c: ({a, b}) => a + b
}

=>

input = {
    a: [],
    b: ['a'],
    c: ['a', 'b']
}

=> 

a => b => c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant