react-model icon indicating copy to clipboard operation
react-model copied to clipboard

[RFC] Derived state in model

Open kyleslight opened this issue 4 years ago • 1 comments

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 avatar May 18 '20 06:05 kyleslight

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

kyleslight avatar May 18 '20 10:05 kyleslight