milankinen / culli

[NOT MAINTAINED] Cycle Utility Libraries for clean, well-structured and concise code
MIT License
24 stars 0 forks source link

Setting initial state for a decomposed Store #8

Open pixeleet opened 7 years ago

pixeleet commented 7 years ago

Hi there,

Quick question, how would I go on about introducing initial state from within a child component instead of passing it directly in main?

milankinen commented 7 years ago

Hmmm. What is the actual use case? If the parent component doesn't have any state yet and you're using partial.lenses, you could use L.defaults. Usage is quite straightforward:

-const {dispatch, props} = model(Store)
+const {dispatch, props} = model(Store.value.select(P(L.defaults(INITIAL_STATE))))
pixeleet commented 7 years ago

hey @milankinen, how about if I wanted to actually set that in the Store, not just default this piece of state to something if it doesn't exist yet?

milankinen commented 7 years ago

Do you mean something like this?

function main({DOM, Store}) {
  const {dispatch, props} = model(Store)
  const vdom = view(props)
  const actions = intent(DOM, Store)

  return {
    DOM: vdom,
    Store: dispatch(O.merge(actions))
  }

  function model({actions, value}) {
    const dispatch = actions.reduce((state, action) => {
      switch (action.type) {
        case "SET_INITIAL":
          return MY_INITIAL_VALUE
        // ....
      }
    })
    return ...
  }

  function view({num}) {
    return ...
  }

  function intent(DOM, store) {
    const setInitialStateAction = store.value
      .filter(val => val === undefined)
      .mapTo({type: "SET_INITIAL"})
      .take(1)
    ...
    return O.merge(setInitialStateAction, ...other actions...)
  }
}
pixeleet commented 7 years ago

@milankinen exactly, because let's say I have a component that is created and I have another component which is curious about the state of that component, but if I just default the value of the store for that component my other component wouldn't know about the default value of that component or I'd have to manually set the state to the same default.