Skip to content

Instantly share code, notes, and snippets.

@joemaffei
Last active September 3, 2019 22:23
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 joemaffei/019d64d73be0d0b39cbc239f5d23f6a5 to your computer and use it in GitHub Desktop.
Save joemaffei/019d64d73be0d0b39cbc239f5d23f6a5 to your computer and use it in GitHub Desktop.
Refactoring React: class method
// Original
tagClick = (tag) => {
let newSpecialties = this.state.specialties.slice();
let specialties = (filter(newSpecialties, (option) => {
return !isEqual(option, tag);
}));
this.setState({ specialties });
}
// 1. Variables are not being reassigned, so they should be consts
tagClick = (tag) => {
const newSpecialties = this.state.specialties.slice();
const specialties = (filter(newSpecialties, (option) => {
return !isEqual(option, tag);
}));
this.setState({ specialties });
}
// 2. slice() does nothing, so newSpecialties doesn't need to exist.
tagClick = (tag) => {
const specialties = (filter(this.state.specialties, (option) => {
return !isEqual(option, tag);
}));
this.setState({ specialties });
}
// 3. We don't need lodash to filter an array.
tagClick = (tag) => {
const specialties = this.state.specialties.filter((option) => {
return !isEqual(option, tag);
});
this.setState({ specialties });
}
// 4. No need to assign a variable outside of the setState.
tagClick = (tag) => {
this.setState({
specialties: this.state.specialties.filter((option) => {
return !isEqual(option, tag);
})
});
}
// 5. Refactor explicit return into implicit return.
tagClick = (tag) => {
this.setState({
specialties: this.state.specialties.filter((option) => !isEqual(option, tag))
});
}
// 6. `specialties` is the plural of `specialty`, not `option`.
tagClick = (tag) => {
this.setState({
specialties: this.state.specialties.filter((specialty) => !isEqual(specialty, tag))
});
}
// 7. We're deriving state from state, so the setState argument needs to be a function.
tagClick = (tag) => {
this.setState((state) => ({
specialties: state.specialties.filter((specialty) => !isEqual(specialty, tag))
}));
}
// 8. We can destructure specialties from state to clean things up.
tagClick = (tag) => {
this.setState(({ specialties }) => ({
specialties: specialties.filter((specialty) => !isEqual(specialty, tag))
}));
}
// 9. `filter` is an array method, so we should make sure that `specialties` is an array.
tagClick = (tag) => {
this.setState(({ specialties = [] }) => ({
specialties: specialties.filter((specialty) => !isEqual(specialty, tag))
}));
}
// 10. This is an event handler, so it should be prefixed with `handle`
handleTagClick = (tag) => {
this.setState(({ specialties = [] }) => ({
specialties: specialties.filter((specialty) => !isEqual(specialty, tag))
}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment