|
| 1 | +import 'babel-polyfill' |
| 2 | +import fetch from 'isomorphic-fetch' |
| 3 | +import React, { Component, PropTypes } from 'react' |
| 4 | +import { controller, getProps } from 'react-redux-controller' |
| 5 | +import * as actions from '../actions' |
| 6 | +import * as selectors from '../selectors' |
| 7 | +import Layout from '../components/Layout' |
| 8 | + |
| 9 | +const controllerGenerators = { |
| 10 | + *initialize() { |
| 11 | + const { selectedReddit } = yield getProps |
| 12 | + |
| 13 | + yield this.fetchPostsIfNeeded(selectedReddit) |
| 14 | + }, |
| 15 | + |
| 16 | + *onSelectReddit(nextReddit) { |
| 17 | + const { dispatch, selectedReddit } = yield getProps |
| 18 | + |
| 19 | + dispatch(actions.selectReddit(nextReddit)) |
| 20 | + |
| 21 | + if (nextReddit !== selectedReddit) { |
| 22 | + yield this.fetchPostsIfNeeded(nextReddit) |
| 23 | + } |
| 24 | + }, |
| 25 | + |
| 26 | + *onRefresh() { |
| 27 | + const { dispatch, selectedReddit } = yield getProps |
| 28 | + |
| 29 | + dispatch(actions.invalidateReddit(selectedReddit)) |
| 30 | + yield this.fetchPostsIfNeeded(selectedReddit) |
| 31 | + }, |
| 32 | + |
| 33 | + *fetchPostsIfNeeded(reddit) { |
| 34 | + const { postsByReddit } = yield getProps |
| 35 | + |
| 36 | + const posts = postsByReddit[reddit] |
| 37 | + if (!posts || !posts.isFetching || posts.didInvalidate) { |
| 38 | + yield this.fetchPosts(reddit) |
| 39 | + } |
| 40 | + }, |
| 41 | + |
| 42 | + *fetchPosts(reddit) { |
| 43 | + const { dispatch } = yield getProps |
| 44 | + |
| 45 | + dispatch(actions.requestPosts(reddit)) |
| 46 | + const response = yield fetch(`http://www.reddit.com/r/${reddit}.json`) |
| 47 | + const responseJson = yield response.json() |
| 48 | + const newPosts = responseJson.data.children.map(child => child.data) |
| 49 | + dispatch(actions.receivePosts(reddit, newPosts)) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +export default controller(Layout, controllerGenerators, selectors) |
0 commit comments