Skip to content

Instantly share code, notes, and snippets.

@jackcallister
Last active October 11, 2015 12:43
Show Gist options
  • Save jackcallister/144e9d9d7654672405f7 to your computer and use it in GitHub Desktop.
Save jackcallister/144e9d9d7654672405f7 to your computer and use it in GitHub Desktop.
Nested Redux Updates
export function updateProp(value, path) {
return {
type: 'UPDATE_PROP',
payload: {
path,
value,
}
}
}
import React, { Component, PropTypes } from 'react'
export default class App extends Component {
static propTypes = {
value: PropTypes.string.isRequired,
updateProp: PropTypes.func.isRequired,
}
render() {
return (
<input value={this.props.value}
onChange={(e) => { this.props.updateProp(e.target.value) }} />
)
}
}
import React, { Component } from 'react'
import { connect } from 'react-redux'
import {
mapStateToProps,
mapDispatchToProps,
mergeProps
} from './appSelectors'
import App from './App'
class AppConnector extends Component {
render() {
return <App {...this.props} />
}
}
export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(AppConnector)
import {
updateProp,
} from './Actions'
export function mapStateToProps(store) {
return {
value: store.data.value,
path: ['value'],
}
}
export function mapDispatchToProps(dispatch) {
return {
updateProp: (path) => {
return (value, extraPath = []) => {
dispatch(updateProp(value, [...path, ...extraPath]))
}
},
}
}
export function mergeEditingProps(stateProps, dispatchProps, ownProps) {
return {
...ownProps,
...stateProps,
...dispatchProps,
updateProp: dispatchProps.updateProp(stateProps.path),
}
}
import set from 'lodash/object/set'
import cloneDeep from 'lodash/lang/cloneDeep'
const initialState = {
value: 'Test'
}
export default function data(state = initialState, action) {
switch(action.type) {
case 'UPDATE_PROP':
return set(
cloneDeep(state),
action.payload.path,
action.payload.value
)
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment