John Gillespie
John Gillespie

Reputation: 87

React JS - getting a separate component to re-render when localStorage state is changed

I have two components. One, called "GenerateRecipesFromList," is a series of "boxes" containing the title of the recipes, and another is a child component, called "AddButon." Right now the Add button can update localStorage, but why does it not "trigger" a change of state and a re-render in the parent component?

My CodePen for this is here

var GenerateRecipesFromList= React.createClass({
    getInitialState: function(){
      const defaultData = [["Spaghetti", "pasta, oil, sauce, parsely, cheese"], ["PB&J", "PB, J"]]
      const localData = JSON.parse(localStorage.getItem('reclist'));
      return {
        reclist: localData ? localData : defaultData
      }
  },  
  render: function(){
    var testData = JSON.parse(localStorage.getItem('reclist'));
    if(testData === null){
        localStorage.setItem('reclist', JSON.stringify(this.state.reclist));
        }
        var currentData = JSON.parse(localStorage.getItem('reclist'));
        var rows = [];
          for(var i=0; i<currentData.length; i++){
        var thedivname = i;
          rows.push(<div id= {this.thedivname} className="individual"> <span><h2>{this.state.reclist[i][0]}</h2></span> 
        </div>);
        }
      return(
        <div className="centerMe">
          <AddButton />
          {rows}
        </div>
      );
    },
});

var AddButton = React.createClass({

      overlayAdd: function() {
        var el = document.getElementById("overlay");
      el.style.visibility = (el.style.visibility === "visible") ? "hidden" : "visible";
      },

      exposeAddRecipe: function(){
          var exposeCurrentData = [];
          var userInput = [];
          exposeCurrentData = JSON.parse(localStorage.getItem('reclist'));
         var newTitle = document.getElementById("title").value;
         var newIngredients = document.getElementById("ingredients").value;

         userInput.push(newTitle);
         userInput.push(newIngredients);
         exposeCurrentData.push(userInput);
          localStorage.setItem('reclist', JSON.stringify(exposeCurrentData));
          this.setState({ reclist: exposeCurrentData});
         this.overlayAdd();
      },

      render: function(){
      return(
        <div>
          <button type="button" id="btnAdd" onClick={this.overlayAdd}>Add a New Recipe</button> 
            <div id="overlay">
             <div>
            <form > 
             <p>Add a new recipe.</p>
             Recipe Title: <input type="text" name="title" id="title" /><br/>
             Ingredients: <input type="text" name="ingredients" id="ingredients" /><br/>
           <button type="button" className="normalBtn" onClick={this.exposeAddRecipe}>Save</button>
           </form>
           <p>Click here to <a href='#' onClick={this.overlayAdd}>close</a></p>

          </div>
        </div> 
      </div>
      );
     }
  });

   var Footer = React.createClass({
   render() {
    return (
      <footer>
        <div id="containerfooter">
          <p>Written by <a  href="http://codepen.io/profaneVoodoo/full/dXBJzN/">John Gillespie</a> for  FreeCodeCamp Campers. Happy Coding!</p>
    </div>
      </footer>
    );
  }
  });


var MyApp = React.createClass({  
  render: function() {
    return(
      <div className = "mainDiv">
         <div className="titleDiv">
       <h1>Recipe Box</h1>

           <GenerateRecipesFromList />
          <Footer />
         </div>        
       </div>
   );
 }, 
}); 

ReactDOM.render(
  <MyApp />,
  document.getElementById('Recipes')
);

Upvotes: 2

Views: 5540

Answers (1)

Anthony Dugois
Anthony Dugois

Reputation: 2052

By calling setState in the AddButton component, you're updating the state of this component instead of the state of the parent.

To update the state of the parent, define a function in the parent component and pass it in the props of AddButton. Then you can call this function in AddButton to update the state of GenerateRecipesFromList.

var GenerateRecipesFromList = React.createClass({
  // ...
  updateRecList: function (reclist) {
    this.setState({ reclist: reclist });
  },
  render: function(){
    // ...
    return(
      <div className="centerMe">
        <AddButton updateRecList={ this.updateRecList } />
        { /* ... */ }
      </div>
    );
  },
});

var AddButton = React.createClass({
  // ...
  exposeAddRecipe: function(){
    // ...
    this.props.updateRecList(exposeCurrentData);
    // ...
  },
  // ...
});

Here is your corrected code.

Upvotes: 2

Related Questions