Search code examples
javascriptreactjsreactjs-flux

ComponentWillMount trigger not stop?


Firstly I'm newbie on React and this is my first project.

I'm creating a basically blog app, my app class like below:

var App = React.createClass({

    getInitialState: function () {
        return {
            posts: Store.getPosts(),
            newPost: {
                headerText: '',
                bodyText: ''
            }
        };
    },

    componentWillMount: function () {
        console.info("App component will mount")
        Store.addChangeListener(this.changeState);
    },

    componentWillUnmount: function () {
        Store.removeChangeListener(this.changeState);
    },

    componentDidMount: function() {
        console.info("App component mounted.")
        Store.removeChangeListener(this.changeState);
    } ,

    changeState: function () {
        this.setState({
            posts: Store.getPosts()
        });
    },

When my app run componentWillMount method triggered and call this.changeState method and it call Store.getPosts() method from flux store.

But this thing don't stop. Continuously call xhr requests from server. My network console like this when app started.

enter image description here

I tried add componentDidMount for solve this but in this case posts don't received from server when app started.

I want just one time load all posts when app started and then run when I call setState method.


Solution

  • you are Call again and again so your store should have method like

     var _post={};
      getDataonly:function()
        {
          return _post;
        },
    

    you have to create a function which can handle the state change and call that function when it's required

    function setpostState()
    {
     return
      {
       post:Store.getPost()
     }
    }
    

    and you have to set this variable when you got the data from api like

      $.ajax({
        type: "GET",
        url : config.serviceURL + "/posts"
      })
          .then(function successCallback(res) {
            if(!res.error) {
              that.posts = res.data;
              _post=res.data;
              that.emitChange();
            } else console.error(res.message);
          })
    

    and your main.js changeState method should be

      changeState: function () {
        this.setState(setpostState());
    },