Skip to content

Instantly share code, notes, and snippets.

@estrattonbailey
Created September 25, 2019 15:23
Show Gist options
  • Select an option

  • Save estrattonbailey/f9bcefd27612eb4f5ade195e8f7903c7 to your computer and use it in GitHub Desktop.

Select an option

Save estrattonbailey/f9bcefd27612eb4f5ade195e8f7903c7 to your computer and use it in GitHub Desktop.
Dataloading
<DataLoader
  cache="events"
  load={async () => {
    const events = await getEvents();
    return events;
  }}
  fallback={() => <Loading />}
>
  {props => {
    return (
      <Events events={props.data} />
    )
  }}
</DataLoader>
import React from 'react'
import { connect } from 'react-redux'
import { initLoading, stopLoading } from '@/state/actions/loadingActions.js'
import { cacheData } from '@/state/actions/dataActions.js'
export default connect((state, props) => {
return {
data: state.data[props.cache]
}
})(
class DataLoader extends React.Component {
constructor (props) {
super(props)
this.state = {
loading: true
}
}
async componentDidMount () {
const { cache, load, dispatch } = this.props
this.setState({ loading: true })
dispatch(initLoading())
const data = await load()
dispatch(cacheData({
[cache]: data
}))
this.setState({ loading: false })
dispatch(stopLoading())
}
render () {
const { loading } = this.state
const {
children,
cache,
render,
fallback = () => null,
data
} = this.props
const component = typeof children === 'function' ? children : render
return loading ? fallback() : component({ data })
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment