FormidableLabs / freactal

Clean and robust state management for React and React-like libs.
MIT License
1.65k stars 46 forks source link

Props in Computed values #82

Closed GHEMID-Mohamed closed 7 years ago

GHEMID-Mohamed commented 7 years ago

Hello :1st_place_medal:

I can't access to props of the component in computed values

const Parent = provideState({
  initialState: () => ({ childId: "16515224" })
})(() => (
  <div>
    This is the Parent.
    <Child id={state.childId}/>
  </div>
));

const Child = provideState({
  initialState: () => ({ name: "Zaki" }),
  computed: {
    childWithId: ({ id, name }) => `${state.name} ${id}`
  }
})(injectState(({ state }) => (
  <div>
    {state.childWithId}
  </div>
));

Do you have any idea of how this can be done ?

divmain commented 7 years ago

There isn't a way to directly get at props from a computed property. Due to freactal's hierarchical nature, it wouldn't be possible to know which prop is being referenced, since the state can come from anywhere higher in the component tree.

However, you can use the pattern of setting initial state from props that are provided. initialState of the Child component accepts props as its argument. So in your example, you would do something like:

const Child = provideState({
  initialState: ({ id }) => ({ id, name: "Zaki" }), // <-- CHANGE MADE ON THIS LINE
  computed: {
    childWithId: ({ id, name }) => `${state.name} ${id}`
  }
})(injectState(({ state }) => (
  <div>
    {state.childWithId}
  </div>
));

I hope that helps!

GHEMID-Mohamed commented 7 years ago

Yes Thank you, that resovle the problem :)