Skip to content

Instantly share code, notes, and snippets.

@R-SE
Last active May 9, 2018 23:58
Show Gist options
  • Save R-SE/d6c3b242981d24b3361f67becc90dd17 to your computer and use it in GitHub Desktop.
Save R-SE/d6c3b242981d24b3361f67becc90dd17 to your computer and use it in GitHub Desktop.
Redux
  1. Create store
  • import { createStore } from 'redux'
  • const store = createStore(mainReducer)
  1. Use Provider to connect react and redux
  • import { Provider } from 'react-redux'
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('app'));

  1. pass props from store
function mapStateToProps(state) {
  return {propName: state.propName}
}

this makes the propName prop available on the component we're connecting below, and can be accessed in the component as this.props.propName

3a) Hook up action creator

function mapDispatchToProps(Dispatch) {
  return bindActionCreators({selectUser: selectUser}, dispatch);
}

this makes actioncreators (similar to event handlers) available to the component: onClick={() => this.props.selectUser(user)}

  1. Hook up component to props & actioncreators made available -- this makes the component into a Container
  • import { connect } from 'react-redux'
  • export default connect(mapStateToProps, mapDispatchToProps)(ComponentName)
  1. Define reducers
  • reducers take the state and an action, and return the new state
  • set a default param for state in your reducer
  1. Combine all reducers
  • combineReducers({users: userReducer, videos: videoReducer})
  1. Set up action creators that return actions
const selectUser = (user) => {
  console.log('Now selecting ', user.first);
  return {
    type: "SELECT_USER",
    payload: user
  }
}

7a) Each action must have a TYPE that's the all-caps description of the action, and optionally a payload

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment