NB! Dynamic Connected Logics are a work in progress! They work, but there are specific issues still left to fix. For more information, please follow this issue.
Dynamic Connected logic
If you need dynamic components (with a key
) that also share data with other components, you will need to connect them in a special way.
You will need to use the withKey(key)
method on the logic and pass it the key
that points to the part of the dynamic logic store that you want to access.
@connect({
props: [
// connecting to a regular logic store
regularLogic, [
'regularField'
],
// connecting to a dynamic logic store,
// we must pass in the key of the dynamic part
dynamicLogic.withKey(12), [
'doneFor12'
],
// connecting to a dynamic logic store,
// the key is derived from the connected component's props
dynamicLogic.withKey(props => props.id), [
'done'
]
]
})
The key
can either be a regular string, number or oter literal... or you can pass a function that calculates it from the props of the component you are connecting to.
In the last example we dynamically passed the key from the id
prop.
Here you can see a complete example:
// create a dynamic logic store
const dynamicLogic = kea({
key: (props) => props.id,
path: (key) => ['scenes', 'dynamic', key],
actions: () => ({
doit: true
}),
reducers: ({ actions, key }) => ({
done: [false, PropTypes.bool, {
[actions.doit]: (state, payload) => key === payload.key ? true : state
}]
})
})
// wrap it around a component
@dynamicLogic
class OnlyData extends Component {
render () {
return <div>OnlyData - id: {this.props.id}, done: {this.props.done ? 'true' : 'false'}</div>
}
}
// create another helper that wants data from this dynamic logic store
@connect({
actions: [
dynamicLogic.withKey(props => props.id), [
'doit'
]
],
props: [
dynamicLogic.withKey(props => props.id), [
'done'
]
]
})
class DataWithButtion extends Component {
render () {
return (
<div>
DataWithButtion - id: {this.props.id}, done: {this.props.done ? 'true' : 'false'}
<button onClick={this.actions.doit}>Do it!</button>
</div>
)
}
}
// main demo
export default class Demo extends Component {
render () {
return (
<div>
<div style={{ border: '1px solid black', padding: 10 }}>
<OnlyData id={123} />
<DataWithButtion id={123} />
</div>
<br />
<div style={{ border: '1px solid black', padding: 10 }}>
<DataWithButtion id={999} />
<OnlyData id={999} />
</div>
</div>
)
}
}
And here you can see it in action:
Next page: Forms