Skip to content

Instantly share code, notes, and snippets.

@ajcrites
Last active September 21, 2018 13:52
Show Gist options
  • Save ajcrites/4e2cef0b1747216dc384ed0201b13a31 to your computer and use it in GitHub Desktop.
Save ajcrites/4e2cef0b1747216dc384ed0201b13a31 to your computer and use it in GitHub Desktop.
// Example
export const profileReducer = function (state = { name: '' }, action) {
switch (action.type) {
case CHANGE_NAME:
return { ...state, name: action.payload };
default:
return state;
}
}
export const Profile = connect(
({ profile: { name } }) => ({ name }),
dispatch => ({ changeName: newName => dispatch(newName.toLowerCase()) }),
)(
({ name, changeName }) => (
<>
<div>{name && name.toUpperCase()}</div>
<button onClick={changeName('NEW NAME')}>change name</button>
</>
),
);
// Better Example
export const profileReducer = function (
state = {
name: '',
lowerCaseName: '',
upperCaseName: '',
},
action,
) {
switch (action.type) {
case CHANGE_NAME:
return {
...state,
...createNameFormats(action.payload),
};
default:
return state;
}
}
function createNameFormats(name = '') {
return {
name,
lowerCaseName: name.toLowerCase(),
upperCaseName: name.toUpperCase(),
};
}
export const Profile = connect(
({ profile: { upperCaseName: name } }) => ({ name }),
dispatch => ({ changeName: newName => dispatch(newName) }),
)(
({ name, changeName }) => (
<>
<div>{name}</div>
<button onClick={changeName('NEW NAME')}>change name</button>
</>
),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment