0

Is there a better way to write this? Like would setState(ContentStore.getAll()) do the same thing? I think this looks needlessly messy, and anyway to streamline the code for legibility would be grand!

class Element extends Component {
 ...
   setContentState = () => {
     const {
      basename,
      bookmark,
      contents,
   } = ContentStore.getAll();

   this.setState({
     basename,
     bookmark,
     contents,
   });
 ...
}

}

ms_nitrogen
  • 220
  • 1
  • 11
  • 2
    Does `ContentStore.getAll()` return an object with any properties you *don't* want to send to `setState`? – CertainPerformance Sep 10 '18 at 00:56
  • This is a special case of [this question](https://stackoverflow.com/questions/25553910/one-liner-to-take-some-properties-from-object-in-es-6) and isn't specific to React or setState. – Estus Flask Sep 10 '18 at 01:21
  • @CertainPerformance No, I am fine with all of it being set to state. Should I just use `this.setState(ContentStore.getAll())`? – ms_nitrogen Sep 10 '18 at 01:53

1 Answers1

1

There is such a convenient function:

const obj = {
  basename: 1,
  bookmark: 2,
  contents: 3,
  aaa: 4
}

const pick = (obj, keys) =>
  Object.assign({}, ...keys.map(key => ({ [key]: obj[key] })))

const picked = pick(obj, ['basename', 'bookmark', 'contents'])

console.log(picked)

Now you can:

const pick = (obj, keys) =>
  Object.assign({}, ...keys.map(key => ({ [key]: obj[key] })))

class Element extends Component {
 ...
   setContentState = () => {
    const data = ContentStore.getAll();
    const result = pick(data, ['basename', 'bookmark', 'contents'])

    this.setState(result);
    ...
  }
}

Or you can use pick function from Lodash or Underscore.

  • It should be noticed that there are existing `pick` functions that don't need to write it from scratch or paste utility function every time. Notably Lodash/Underscore `pick`. – Estus Flask Sep 10 '18 at 01:21