Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HOC? #5

Closed
goncy opened this issue Apr 4, 2018 · 1 comment
Closed

HOC? #5

goncy opened this issue Apr 4, 2018 · 1 comment

Comments

@goncy
Copy link

goncy commented Apr 4, 2018

Do you plan creating a HOC like connect for like dispatching actions on componentDidMount and having state available on those steps

@diegohaz
Copy link
Owner

diegohaz commented Apr 4, 2018

Hi, @goncy.

I have no plans to provide a HOC on this library, unless a lot of people actually demand it. I suggest you and other people interested on this topic to watch this talk by @mjackson: Never Write Another HoC.

That said, this is how a HOC implementation of State could look like:

const withState = stateProps => Component => props => (
  <State {...stateProps}>
    {state => <Component {...props} state={state} />}
  </State>
);

const enhance = withState({
  initialState: { count: 0 },
  actions: {
    increment: amount => state => ({ count: state.count + amount })
  },
  context: 'counter1'
});

const CounterValue = enhance(({ state }) => (
  <div>{state.count}</div>
));

One of the drawbacks is that you need to pass stateProps statically to withState. You can't pass context from within CounterValue for example.

I recommend you to stick with render props and use one of the following approaches to access state in React lifecycles:

  1. Create another component:
class Component extends React.Component {
  componentDidMount() {
    this.props.increment(1);
  }

  render() {
    return <div>{this.props.count}</div>;
  }
}

const Counter = () => (
  <CounterState context="counter1">
    {state => <Component {...state} />}
  </CounterState>
);
  1. Use https://github.com/reactions/component:
import Component from "@reactions/component";

const Counter = () => (
  <CounterState context="counter1">
    {({ count, increment }) => (
      <Component didMount={() => increment(1)}>
        <div>{count}</div>
      </Component>
    )}
  </CounterState>
);

I'm going to close this issue for now. But I can reopen in the future if people really want HOCs.

@diegohaz diegohaz closed this as completed Apr 4, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants