This a working function as part of a drag and drop task manager im playing around with. The function is working fine, but it just looks messy and long to me. I haven't added all the code as I'm looking just to tidy up the function itself. I have added the state though as guidance.
function
onDrop = () => {
let people = [...this.state.people]
let newPeopleArray = []
let newChoresArray = []
let personToUpdate = {}
people.forEach( person => {
if ( person.name !== this.state.targetPerson ) {
newPeopleArray.push(person)
} else {
personToUpdate = person
personToUpdate.chores.forEach( chore => {
if ( chore !== this.state.targetChore ) {
newChoresArray.push(chore)
}})
personToUpdate.chores = newChoresArray
}})
newPeopleArray.push(personToUpdate)
this.setState ({ people: newPeopleArray})
}
state
class App extends Component {
state = {
targetChore: '',
targetPerson: '',
people: [
{ name: 'Grace', chores: ['clean kitchen', 'wash dog', 'laundry'] },
{ name: 'Sam', chores: ['walk dog', 'wash car', 'go shopping'] },
{ name: 'Rose', chores: ['wash windows', 'vaccum', 'clean bathroom'] }
]
}
-
\$\begingroup\$ I update my question let me know what you think about it . I prefer object oriented programming \$\endgroup\$fabOnReact– fabOnReact2019年04月27日 09:27:25 +00:00Commented Apr 27, 2019 at 9:27
-
\$\begingroup\$ Thanks @FabrizioBertoglio, its an interesting take and a completely different method which is interesting! I need to explore OOP more. Thank you! \$\endgroup\$gracie catherine– gracie catherine2019年05月06日 17:36:09 +00:00Commented May 6, 2019 at 17:36
-
\$\begingroup\$ Yes. I find Object Oriented programming is easier to refactor and mantain, as it already iherints properties from real world objects .. It is easier to copy something from the real world instead of re-inventing everything \$\endgroup\$fabOnReact– fabOnReact2019年05月06日 18:02:22 +00:00Commented May 6, 2019 at 18:02
1 Answer 1
A Person
class encapsulates the attributes/methods and logic for the Person
object. Currently inherits from Object
, but you can at any time extend this logic by creating an new super class or children and distribute the logic between those hierarchies.
class Person extends Object {
constructor(props) {
super
this.name = props.name
this.chores = props.chores
}
addSubject() {
if (this.isFound) { return new People().push(person) }
// your choice to either create a chore class or write some subroutine
else { person.chores.forEach( chore => chore.addChore ) }
}
// either pass targetPerson as param or add it to the Person object as attribute
isFound() { this.name !== this.state.targetPerson }
}
people = [ new Person('Grace', 'clean kitchen', 'wash dog'..), etc..]
I also believe the onDrop
subroutine should just have the responsibility of dropping person
or returning
a new people
object. It would be an instance method
of the People
class
class People extends Object {
drop = () => {
this.each( person => person.addSubject() )
// etc...
}
}