user220409
user220409

Reputation: 184

How to get to work mobx + react + ui components?

In the project I'm using ui components in the code below is expressed in the form of pseudo clock.
How to make this code work without changing the code clock which in reality is an external library.

And the most important thing that the decision was in the spirit of mobx.

class ClockStore {
    @observable data = [
        {id: "hour", value: "00"},
        {id: "min", value: "00"},
        {id: "second", value: "00"},
    ];

    @action
    update(id, value){
        this.data.find(item => item.id === id).value = value;
    }
}

let clockStore = new ClockStore();



@inject('clockStore')
@observer
class App extends Component<any, any> {
    render(){
        return <Clock data={this.props.clockStore.data}></Clock>
    }
}

// it's not my clock this component is taken from github
class Clock extends Component<any, any> {
    render(){
        return (
            <div>
                <ClockFace data={this.props.data} />
                <div className="clock-control"></div>
            </div>
        )
    }
}

class ClockFace extends Component<any, any> {
    render(){
        return (
            <div className="clock-face">
                {this.props.data.map( ( item, index ) => <ClockSection key={ index }>{ item.value }</ClockSection> )}
            </div>
        )
    }
}
class ClockSection extends Component<any, any> {
    render(){
        return (
            <span className="clock-section">{ this.props.children }</span>
        )
    }
}

let stores = { clockStore };

ReactDOM.render(
    <Provider {...stores}>
        <App />
    </Provider>,
    document.querySelector( 'main' )
);

// the code that sets the clock
let count = 0;
document.addEventListener( 'click', () => clockStore.update( 'hour', count ++ ) );
// --------------------------

Upvotes: 0

Views: 374

Answers (1)

user220409
user220409

Reputation: 184

@inject('clockStore')
@observer
class App extends Component<any, any> {
    render(){
        return <Clock data={ mobx.toJS( this.props.clockStore.data } }></Clock>
    }
}

or

class ClockStore {
    @observable data = [
        {id: "hour", value: "00"},
        {id: "min", value: "00"},
        {id: "second", value: "00"},
    ];

    getData(){
        return toJS( this.data );
    }

    @action
    update(id, value){
        this.data.find(item => item.id === id).value = value;
    }
}
@inject('clockStore')
@observer
class App extends Component<any, any> {
    render(){
        console.log( 'app' );


        return <Clock data={this.props.clockStore.getData()}></Clock>
    }
}

Upvotes: 1

Related Questions