Last active
March 9, 2018 06:44
-
-
Save PabloAlexandre/3eccdc0973a4d6d8d65d7842c1d32a78 to your computer and use it in GitHub Desktop.
Connect to bind actions with component state.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from 'react'; | |
| class Connect extends React.Component { | |
| constructor(props){ | |
| super(props); | |
| this.actions = this.getActions(this.props.actions); | |
| this.state = this.props.state || {}; | |
| } | |
| getActions(actions){ | |
| return Object.entries(actions).reduce((keep, [k, v]) => { | |
| if(typeof v === "function") return {...keep, [k]: v.bind(this)} | |
| else if (typeof v === "object") return {...keep, [k]: this.getActions(v)}; | |
| }, {}); | |
| } | |
| render() { | |
| return this.props.children({ | |
| ...this.actions, | |
| ...this.state | |
| }) | |
| } | |
| } | |
| export function connect(state, actions) { | |
| return Child => class ConnectWrapper extends React.Component { | |
| render() { | |
| const { props } = this; | |
| return ( | |
| <Connect actions={actions} state={state}> | |
| { mappedProps => <Child {...mappedProps } {...props} /> } | |
| </Connect> | |
| ) | |
| } | |
| } | |
| } | |
| /* EXAMPLE | |
| const initialState = { | |
| username: '', | |
| timezone: '' | |
| } | |
| const actions = { | |
| setUsername(username){ | |
| this.setState({username}) | |
| }, | |
| utils: { | |
| setTimezone(timezone){ | |
| this.setState({timezone}) | |
| } | |
| } | |
| } | |
| connect(initialState, actions)(({ utils, setUserName }) => ( | |
| <Fragment> | |
| <button onClick={() => setUserName('MyUsername')} /> | |
| <button onClick={() => utils.setTimezone('America/Sao_Paulo')} /> | |
| </Fragment> | |
| )) | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment