Last active
September 13, 2018 14:12
-
-
Save mqklin/84b23a032872213ad5e55dca366e01d2 to your computer and use it in GitHub Desktop.
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
// getContext.js | |
import React, {Component} from 'react'; | |
const {Provider, Consumer} = React.createContext(); | |
const getContext = keys => WrappedComponent => props => ( | |
<Consumer> | |
{state => ( | |
<WrappedComponent | |
{...keys.reduce((acc, key) => ((acc[key] = state[key]), acc), {})} | |
{...props} | |
/> | |
)} | |
</Consumer> | |
); | |
export default getContext; | |
export {Provider}; | |
// Root.js | |
/* global module */ | |
import {hot} from 'react-hot-loader'; | |
import React, {Component} from 'react'; | |
import App from './App'; | |
import {myAxios} from 'App/utils'; | |
import {Provider} from './getContext'; | |
@hot(module) | |
export default class Root extends Component { | |
state = { | |
project: {}, | |
}; | |
fetchProject = () => { | |
return myAxios.fetch('project') | |
.then(({data}) => this.setState(() => ({project: data}))); | |
}; | |
render() { | |
const {fetchProject, state: {project}} = this; | |
return ( | |
<Provider | |
value={{ | |
project, | |
fetchProject, | |
}} | |
> | |
<App/> | |
</Provider> | |
); | |
} | |
} | |
// SomeDeepComponent.js | |
import React, {Component} from 'react'; | |
import styled from 'styled-components'; | |
import {object, func} from 'prop-types'; | |
import getContext from 'getContext'; // webpack alias | |
const Wr = styled.div` | |
font-size: 24px; | |
`; | |
@getContext(['fetchProject, project']) | |
export default class SomeDeepComponent extends Component { | |
static propTypes = { | |
project: object.isRequired, | |
fetchProject: func.isRequired, | |
}; | |
componentDidMount() { | |
const {fetchProject} = this.props; | |
fetchProject(); | |
} | |
render() { | |
const {project} = this.props; | |
return ( | |
<Wr> | |
Project name is {project.name || '...'} | |
</Wr> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment