Last active
August 30, 2016 00:35
-
-
Save fraserxu/91a9d3669e0d27803fc679ba28536c60 to your computer and use it in GitHub Desktop.
getQueriesTree
This file contains 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
const getPropsFromChild = (child) => { | |
const { props, type } = child | |
let ownProps = Object.assign({}, props) | |
if (type && type.defaultProps) ownProps = Object.assign({}, type.defaultProps, props) | |
return ownProps | |
} | |
const getChildFromComponent = (component) => { | |
// See if this is a class, or stateless function | |
if (component && component.render) return component.render() | |
return component | |
} | |
let contextStore = {} | |
const getQueriesFromTree = ({component, context = {}, queries = []}, fetch) => { | |
if (!component) return | |
// stateless function | |
if (typeof component === 'function') component = { type: component } | |
const { type, props } = component | |
// console.log('component', component) | |
if (typeof type === 'function') { | |
let ComponentClass = type | |
let ownProps = getPropsFromChild(component) | |
const Component = new ComponentClass(ownProps, context) | |
try { Component.props = ownProps; } catch(e) {} // eslint:disable-line | |
if (Component.componentWillMount) Component.componentWillMount() | |
let newContext = context | |
if (Component.getChildContext) newContext = Object.assign({}, context, Component.getChildContext()) | |
// see if there is a fetch data method | |
if (typeof type.fetchData === 'function') { | |
const query = type.fetchData(ownProps, newContext) | |
if (query) queries.push({ query, component }) | |
} | |
getQueriesFromTree({ | |
component: getChildFromComponent(Component), | |
context: newContext, | |
queries, | |
}) | |
} else if (props && props.children) { | |
Children.forEach(props.children, (child) => getQueriesFromTree({ | |
component: child, | |
context, | |
queries | |
})) | |
} | |
return { queries, context: contextStore } | |
} | |
const component = ( | |
<Button /> | |
) | |
console.log('tree', getQueriesFromTree({component})) | |
// tree { queries: [ { query: 'test', component: [Object] } ], context: {} } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment