Support Control Props for all state

Kent C. Dodds
InstructorKent C. Dodds
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 4 years ago

Our current implementation of control props only supports controlling the state of a single item of state. Let's make our solution more generic to support any and all state of our component using Object.entries.

Instructor: [00:00] Let's go and refactor this so it's a little bit more capable. Right now, it only supports the onState, but if your component has more than just a couple items of state, it might be a little tedious to keep this updated.

[00:10] What we are going to do is take our state object and return a new object that combines our controlled and uncontrolled state. Here, we will return objects.entries this.state, and we'll reduce that within arrow function and we'll initialize our reducer with an empty object.

[00:28] The accumulator for this reducer function is going to be our combined state. We'll de-structure each of the entries to their key and value.

[00:37] We will return our combined state and we'll say if this.is controlled key, then our combineStateAtThatKey will equal this.propsAtThatKey. Otherwise, combineStateAtThatKey will be the value because that's coming from state.

[00:57] Now everything is working just as well. This makes our getState function more capable because now it will continue to work regardless of what changes we make to our state.

Karl Purkhardt
Karl Purkhardt
~ 6 years ago

Hi Kent. Is there any reason you've used an if/else and mutated the object here over using object spread, a ternary and computed properties? Seems cleaner to use the latter:

getState() {
    return Object.entries(this.state).reduce(
      (combinedState, [key, value]) => ({
        ...combinedState,
        [key]: this.isControlled(key) ? this.props[key] : value
      }),
      {}
    )
  }

I believe they're functionally equivalent, and appreciate the former is easier to digest if you're not used to these language features, but this an advanced course and you've not shied away from these features in previous episodes so I was curious.

Kent C. Dodds
Kent C. Doddsinstructor
~ 6 years ago

I honestly hadn't considered that 💯

Markdown supported.
Become a member to join the discussionEnroll Today