0

I wanted to learn recompose so I started with a simple component component:

const timer: React.SFC<MyProps | any> = ({ seconds }) => (
  <span>{ seconds }</span>
);

I'd like to somehow pass seconds to it using recompose, where it would increment each second.

let seconds = 0;
export default compose(
  withProps(() => ({ seconds })),
  pure,
)(Timer);

How can I properly increment seconds props so it is propagated to the component on props change? I tried adding recurrsive function with setTimeout after let seconds declaration but it doesn't propagate down to the component on change.

I ended up with this

let seconds = 0;

incrementSeconds();

function incrementSeconds() {
  seconds += 1;
  setTimeout(
    () => {
      incrementSeconds();
    },
    1000,
  );
}

export default compose(
  withProps(() => ({ seconds })),
  pure,
)(Timer);
simPod
  • 11,498
  • 17
  • 86
  • 139

1 Answers1

1

Instead of withProps, I would make use of withState and then update the state like

export default compose(
  withState('seconds', 'updateSeconds', 0),
  lifecycle({
     componentDidMount() {
         const { seconds, updateSeconds} = this.props;
         setTimeout(
            () => {
               updateSeconds(seconds + 1);
            },
            1000,
         );
     }
  }),
  pure,
)(Timer);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400