Skip to content

Instantly share code, notes, and snippets.

@sdtsui
Last active March 24, 2016 03:22
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 sdtsui/7bd3ea5b8903ad4fe206 to your computer and use it in GitHub Desktop.
Save sdtsui/7bd3ea5b8903ad4fe206 to your computer and use it in GitHub Desktop.
marty-to-redux-cliffs-notes.md

1:1 - Constants : const

Action creators : functions

  export function updateEmail (userId, email) {
    return {
      type: 'UPDATE_EMAIL',
      payload: { userId, email }
    }
  }

1:1 - Stores : reducers

  export default function (state = new Immutable.Map(), action) {
    switch (action.type) {
      case 'RECEIVE_USER':
        const {user} = action.payload

        return state.set(user.get('id'), user)
      default:
        return state
    }
  }

1:1 - Render : [applyMiddleWare, combineReducers, createStore, Provider wrap]

  React.render((
    <Provider store={store}>
      {() => <Handler />}
    </Provider>
  ), document.getElementById('app'))
  

1:1 - Containers : Container Components

  const getVisibleTodos = (todos, filter) => {
    switch (filter) {
      case 'SHOW_ALL':
        return todos
      case 'SHOW_COMPLETED':
        return todos.filter(t => t.completed)
      case 'SHOW_ACTIVE':
        return todos.filter(t => !t.completed)
    }
  }

  const mapStateToProps = (state) => {
    return {
      todos: getVisibleTodos(state.todos, state.visibilityFilter)
    }
  }

  const mapDispatchToProps = (dispatch) => {
    return {
      onTodoClick: (id) => {
        dispatch(toggleTodo(id))
      }
    }
  }

  import { connect } from 'react-redux'

  const VisibleTodoList = connect(
    mapStateToProps,
    mapDispatchToProps
  )(TodoList)

  export default VisibleTodoList

1:1 - async fetches : thunk (dispatching functions)

  const store = createStore(
    rootReducer,
    applyMiddleware(
      thunkMiddleware, // lets us dispatch() functions
      loggerMiddleware // neat middleware that logs actions
    )
  )

  store.dispatch(selectSubreddit('reactjs'))
  store.dispatch(fetchPosts('reactjs')).then(() =>
    console.log(store.getState())
  )

  import fetch from 'isomorphic-fetch'

  export const REQUEST_POSTS = 'REQUEST_POSTS'
  function requestPosts(subreddit) {
    return {
      type: REQUEST_POSTS,
      subreddit
    }
  }

  export const RECEIVE_POSTS = 'RECEIVE_POSTS'
  function receivePosts(subreddit, json) {
    return {
      type: RECEIVE_POSTS,
      subreddit,
      posts: json.data.children.map(child => child.data),
      receivedAt: Date.now()
    }
  }

  function fetchPosts(subreddit) {
    return dispatch => {
      dispatch(requestPosts(subreddit))
      return fetch(`http://www.reddit.com/r/${subreddit}.json`)
        .then(response => response.json())
        .then(json => dispatch(receivePosts(subreddit, json)))
    }
  }

  function shouldFetchPosts(state, subreddit) {
    const posts = state.postsBySubreddit[subreddit]
    if (!posts) {
      return true
    } else if (posts.isFetching) {
      return false
    } else {
      return posts.didInvalidate
    }
  }

  export function fetchPostsIfNeeded(subreddit) {

    // Note that the function also receives getState()
    // which lets you choose what to dispatch next.

    // This is useful for avoiding a network request if
    // a cached value is already available.

    return (dispatch, getState) => {
      if (shouldFetchPosts(getState(), subreddit)) {
        // Dispatch a thunk from thunk!
        return dispatch(fetchPosts(subreddit))
      } else {
        // Let the calling code know there's nothing to wait for.
        return Promise.resolve()
      }
    }
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment