Batman
Batman

Reputation: 6353

Update component when prop value changes

I have an object with the property home.ready = false. When the object is done getting data, cleaning it etc it changes to home.ready= true.

I need my component to register the change and update. My component:

 class HomeNav extends React.Component {
      render() {
          let data = this.props.data;
          let uniqueTabs = _.uniq(_.map(data, x => x.tab)).sort();

          let tabs = uniqueTabs.map((tab, index) => {
              let itemsByTab = _.filter(data, (x => x.tab == tab));
              return <Tabs key={tab} tab={tab} index={index} data={itemsByTab} />;
          });
          console.log(this.props)
          return (
              <section>
                  <div className="wb-tabs">
                      <div className="tabpanels">
                        { this.props.ready ? {tabs} : <p>Loading...</p> }
                      </div>
                  </div>
              </section>
          )
      }
  };

ReactDOM.render(
  <HomeNav data={home.data.nav} ready={home.ready}/>,
  document.getElementById('home-nav')
);

This is the home object. It's a simple object that gets data and once the data is ready the property ready changes from false to true. I can't get React to recognize that change. And at times React will say home is undefined.

Upvotes: 0

Views: 92

Answers (1)

Hugo Silva
Hugo Silva

Reputation: 6938

Since you didn't post any code around the request, or data formatting, I will assume you got all that figured out. So, for your component to work the way it is currently written, you need to drop the curly braces around tabs ({ this.props.ready ? tabs : <p>Loading...</p> }), then, this.props.data should always contain a valid Array, otherwise it will break when you try to sort, filter, etc.


Or, you can do an early dropout, based on the ready property:

class HomeNav extends React.Component {
      render() {
          if(!this.props.ready){
              return <section>
                  <div className="wb-tabs">
                      <div className="tabpanels">
                          <p>Loading...</p>
                      </div>
                  </div>
              </section>
          }

          let data = this.props.data;
          let uniqueTabs = _.uniq(_.map(data, x => x.tab)).sort();

          let tabs = uniqueTabs.map((tab, index) => {
              let itemsByTab = _.filter(data, (x => x.tab == tab));
              return <Tabs key={tab} tab={tab} index={index} data={itemsByTab} />;
          });
          console.log(this.props)
          return (
              <section>
                  <div className="wb-tabs">
                      <div className="tabpanels">
                        {tabs}
                      </div>
                  </div>
              </section>
          )
      }
  };

Upvotes: 1

Related Questions