1

Quick question about destructuring in React

state = {
 cat: 'meow',
 dog: 'bark',
 fish: 'what sound do i make?',
 snake: 'im not wanted for this experiment',
 turtle: 'im also not wanted for this experiment'
}

const {cat, dog, fish } = this.state;
const animals = { cat, dog, fish };
this.pets(animals)

This is obviously just an example but I find myself in similar situations when I'm destructuring by retyping the same variables. I'm hoping there was easier way of doing this? Something like this:

const animals = {cat, dog, fish} = this.state

Or Is it a bad practice to pass the variables directly into the function? (it could end up being a long list of variables)

const {cat, dog, fish} = this.state
this.pets(cat, dog, fish}
Eddie
  • 26,593
  • 6
  • 36
  • 58
learnerforlife
  • 189
  • 1
  • 3
  • 15
  • 1
    `this.pets({ cat, dog, fish })` seems fine to me. – p.s.w.g Apr 26 '19 at 16:03
  • 1
    Depends on how large your state is, but you could do `const { snake, turtle, ...animals }; this.pets(animals);` – Tholle Apr 26 '19 at 16:04
  • 1
    Hmmm...assuming you have control over the `pets` method, I'd make it take an object and destructure what it needs out of it. Otherwise it's coupled to the method you're calling it from (that method needs to know that it needs specific things from state). That isn't the worst thing ever, but seems easy enough to avoid here. – Jared Smith Apr 26 '19 at 16:07
  • 1
    Are you looking for this https://stackoverflow.com/questions/17781472/how-to-get-a-subset-of-a-javascript-objects-properties ? – str Apr 26 '19 at 16:07

0 Answers0