Demo entry 6362636

TC Test

   

Submitted by anonymous on May 09, 2017 at 17:48
Language: JavaScript. Code size: 2.2 kB.

// @flow
import React from 'react'
import { omit } from 'ramda'
import { compose, wrapDisplayName, setDisplayName, getContext } from 'recompose'
import { layerContextShape } from './LayerProvider'

type QueryT = {
  on: (string, () => mixed) => mixed,
  off: (string, () => mixed) => mixed,
  destroy: () => mixed,
  data: ?Object | Array<Object>,
}

type LayerClientT = {
  isReady: boolean,
  createQuery: () => QueryT,
  on: () => mixed,
  off: () => mixed,
}

type PropsT = {
  layerClient: LayerClientT,
}

type StateT = {
  data: ?Object | Array<Object>,
  query: ?Object,
}

type MakeQueryT = Object => mixed

const removeInternalProps = omit(['layerClient'])

const withLayerQuery = (makeQuery: MakeQueryT) => (
  Component: ReactClass<any> // eslint-disable-line no-undef
) => {
  const enhance = compose(
    setDisplayName(wrapDisplayName(Component, 'withLayerQuery')),
    getContext(layerContextShape)
  )
  class HOC extends React.Component<void, PropsT, StateT> {
    state = { data: null, query: null }

    componentDidMount() {
      this.startQuery()
    }

    componentWillUnmount() {
      this.stopQuery()
    }

    startQuery = () => {
      const { layerClient: client } = this.props
      if (client.isReady) {
        const arg = makeQuery(client, this.props)
        if (!arg) return
        const query = client.createQuery(arg)
        query.on('change', this.onQueryChange)
        this.setState({ query })
      } else {
        client.on('ready', this.startQuery)
      }
    }

    stopQuery = () => {
      if (this.state.query) {
        this.state.query.off('change', this.onQueryChange)
        this.setState({ query: null })
      }
    }

    onQueryChange = evt => {
      if (!this.state.query) return
      const { data } = this.state.query
      this.setState({ data })
    }

    render() {
      const { data, query } = this.state
      if (!query || !data || !data.length) return null
      return (
        <Component
          {...removeInternalProps(this.props)}
          data={data}
          query={query}
        />
      )
    }
  }

  return enhance(HOC)
}

export default withLayerQuery

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).