Search code examples
reactjsrecompose

Using withState and lifecycle from recompose together


I would like to build a component that randomly updates numeric props to different positions on a chessboard.

In order to do this, I created a simple component with an interval:

JSFIDDLE: https://jsfiddle.net/ezxnjc8h/

export default class RandomPosition extends React.Component {
    constructor(props) {
        super(props)
        this.interval = null;
        this.state = {
            x: 0,
            y: 0
        }
    }

    componentDidMount() {
        this.interval = setInterval(() => {
            this.setState({
                x: Math.floor(Math.random() * 8),
                y: Math.floor(Math.random() * 8)
            })
        }, 500)
    }

    componentWillUnmount() {
        clearInterval(this.interval)
    }

    render() {
        return <Test knightPosition={[this.state.x, this.state.y]} moveKnight={this.props.moveKnight} />
    }
}

I am interested in converting the same to a Hoc using the recompose library using withState and lifecycle to do so.

JSFIDDLE: https://jsfiddle.net/kzwc9yha/

export default compose(
    withState('knightPosition', 'moveKnight', [1,7]),
    lifecycle({
        componentDidMount() {
           this.interval = setInterval(() => {
               this.props.moveKnight[Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)]
            }, 500)
        },
        componentWillUnmount() {
            clearInterval(this.interval)
        }
    })
)(Test)

Solution

  • There are a couple of issues in your fiddle.

    First: You haven't imported lifecycle from Recompose

    Second: moveKnight is a function and hence it needs to be invoked like

     this.interval = setInterval(() => {
             this.props.moveKnight(
                 [Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)]
             );
        }, 500)
    

    Working DEMO