Search code examples
javascriptreactjsrefluxjs

own timer component with react, reflux not working


I try to get used to reflux and forked a example repo. My full code is here [ https://github.com/svenhornberg/react-starterkit ]

I want to create a timer component which gets the current time from a timestore, but it is not working. The DevTools does not show any errors. This must be some newbie mistakes, but I do not find them.

Edit1: I added a line in home //edit1

Edit2: I think the mistake may be in componentDidMount in home.jsx

FIXED I need to trigger my time, see my answer.

Store

import Reflux from 'reflux';
import TimeActions from '../actions/timeActions';

var TimeStore = Reflux.createStore({
    listenables: timeActions,

    init() {
        this.time = '';
    },

    onCurrenttime() {
        this.time = '13:47';
    }
});

export default TimeStore;

Actions

import Reflux from 'reflux';

var TimeActions = Reflux.createActions([
  'currenttime'
]);

export default TimeActions;

Component

import React from 'react';

class Timer extends React.Component {

  constructor(){
    super();    
  }

  render() {
    var time = this.props.time;

    return (
      <div>
        { time }
      </div>
    );
  }

}

Timer.propTypes = {
  time : React.PropTypes.string
}

export default Timer;

I wanted to use the timer component in the home.jsx

import React from 'react';
import ItemList from '../components/itemList.jsx';
import ItemStore from '../stores/itemStore';
import ItemActions from '../actions/itemActions';

import Timer from '../components/timer.jsx';
import TimeStore from '../stores/timeStore';
import TimeActions from '../actions/timeActions';

class Home extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      items : [],
      loading: false,
      time : '' //edit1
    };
  }

  componentDidMount() {
    this.unsubscribe = ItemStore.listen(this.onStatusChange.bind(this));
    this.unsubscribe = TimeStore.listen(this.onStatusChange.bind(this));

    ItemActions.loadItems();
    TimeActions.currenttime();
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  onStatusChange(state) {
    this.setState(state);
  }

  render() {

    return (
      <div>
        <h1>Home Area</h1>
        <ItemList { ...this.state } />
        <Timer { ...this.state } />
      </div>
    );
  }
}

export default Home;

Solution

  • I fixed it thanks to: How to Make React.js component listen to a store in Reflux

    I have to trigger my time:

    var TimeStore = Reflux.createStore({
        listenables: TimeActions,
    
        init() {
            this.time = '';
        },
    
        onCurrenttime() {
          this.trigger({
            time : '13:47'
          });
        }
    });