Skip to content

Instantly share code, notes, and snippets.

@fraserxu
Last active August 30, 2016 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fraserxu/91a9d3669e0d27803fc679ba28536c60 to your computer and use it in GitHub Desktop.
Save fraserxu/91a9d3669e0d27803fc679ba28536c60 to your computer and use it in GitHub Desktop.
getQueriesTree
import React from 'react'
class Button extends React.Component {
static fetchData (props, context) {
return 'test'
}
render () {
return <button>not a button</button>
}
}
export default Button
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