Search code examples
javascriptreactjs-fluxreactjs

Why is this.state.name not being used properly in my component?


I have a teamName store that stores the name of the team and changes on depending on whether a name is clicked/hovered.

TeamStore.js:

function setName(name) {
    _team = name;
    _original = name;
}

//set a temp team name when sidemenu item is being hovered
function setHover(team) {
    _original = _team;
    _team = team;
}

function removeHover() {
    //console.log(_original);
    _team = _original;
}

I also have ThumbNail.jsx that listens to this store and triggers an _updateArticle method when this.state.name changes. However, its not working properly.

  • the articles don't change when the item is being hovered.
  • the articles change to the hovered item on hover leave (which they shouldn't) they should go back to original one that was clicked.

ThumbNail.jsx:

var ThumbNail = React.createClass({
    mixins: [ReactFireMixin],

    getTeamState() {
        return  TeamStore.getSelected() ;
    },

    getInitialState() {
        return {
            name: this.getTeamState(),
            articles: []
                };
    },

    getDefaultProps() {
        return {
            baseUrl: "https://shining-inferno-1085.firebaseio.com/"
        }
    },


    _updateArticle() {
        //console.log(this.state.name);
        var teamRef = new Firebase(this.props.baseUrl + this.state.name + "/results");

        this.bindAsArray(teamRef, 'articles');

    },

    componentDidMount() {

        TeamStore.addChangeListener(this._onChange);
        this._updateArticle();
    },

    componentWillUnmount() {
        TeamStore.removeChangeListener(this._onChange);
        this.unbind("articles");
    },

    render() {

        return (

            <ul className="tiles">
                <BasicInfo article={this.state.articles} />
            </ul>
            )   
    },

    _onChange() {
        var team = this.getTeamState();
        this.setState({name: team});
        //console.log(this.props.baseUrl + this.state.name + "/results");
        this.unbind("articles");
        this._updateArticle();
    }


});


module.exports = ThumbNail;

P.S I have a title component that listens to the same store and works fine. Let me know if you need that.

Edit: Care to explain the downvote?


Solution

  • This problem could be similar to this.

    setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.