// Functional Style: half the size!
import PropTypes from 'prop-types'
import { useSelector, useDispatch, shallowEqual } from 'react-redux'

import makeSelectHackerNews from './selectors'
import { fetch } from './actions'

function useHackerNews(props) {
  const hackerNews = useSelector(makeSelectHackerNews, shallowEqual)
  const dispatch = useDispatch()

  useEffect(() => {
    if (!hackerNews.data.length && !hackerNews.fetching) {
      dispatch(fetch({
        offset: 0,
        limit: 15,
      }))
    }    
  }, [hackerNews])

  return hackerNews
}

export default function HackerNews({ children, ...props }) {
  const hackerNews = useHackerNews(props)
  return children(hackerNews)
}

HackerNews.propTypes = {
  children: PropTypes.func.isRequired,
}