0

I'm using React context for state management and code climate doesn't like the repetition around Context Providers.

enter image description here

Is there any way that I can remove the duplication?

2
  • 2
    That doesn't seem like a duplication to me as both context providers are providing a specific part of state. I find it readable this way and will rather relax the CodeClimate rule. You can however implement a high order component that wraps child component in a generic react provider and receives provider values as props. Commented Feb 26, 2019 at 11:46
  • Sorry, 'Similar code' was the exact phrasing I think. Can you elaborate on the hoc approach by any chance? I don't understand how I would create make one generic provider with different values as props. Commented Feb 26, 2019 at 13:09

1 Answer 1

1

The Code climate rule can be relaxed for this particular code.

That said, you can transform the current usage of context to a React component exposing its props as a channel to provide values in a generic context provider.

For example, a WithCollection component which forwards its props to a generic CollectionContext.Provider can be created. The consolidates the function TasksContext.Provider and CommentsContext.Provider in CollectionContext.Provider.

class WithCollection extends React.Component {
  render() {
    const {children, ...value} = this.props
    return (
      <CollectionContext.Provider value={value}>
      {children}
      </CollectionContext.Provider>
    );
  }
}

The usage of which is represented as follow:

<WithCollection tasks={this.state.tasks}>
//...
</WithCollection>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.