Recipe Box - getting data to display from local storage

Recipe Box - getting data to display from local storage
0

#1

Hi, everyone. I am still struggling with some ReactJS basics. For example, I want to pull data that is in local browser storage and display it. Below is the approach I am taking, yet nothing renders.

Please could someone point me in the right direction?

View my codepen for this here

var GenerateRecipeFromList= React.createClass({
    getInitialState: function(){
      
      var spaghetti = [
          'Spaghetti', 
          'pasta', 
          'oil', 
          'sauce', 
          'cheese'];
      localStorage.spaghetti = JSON.stringify(spaghetti); 
      
       return JSON.parse(localStorage.getItem('spaghetti'));
    },
    render: function(){
      return(
        <div>
        <span>{this.state.spaghetti}</span>
        <button type="button"  id="btnAdd">Add a Recipe</button>
        </div>
      );
    }
  });

var DisplayRecipes = React.createClass({
  
  render:function(){
    return(
      <div className = "mainDiv">
          <div className="titleDiv">
        <h1>Favorite Recipes</h1>
        <GenerateRecipeFromList />
          </div>        
        </div>
    );
  }
});

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

#2

Your first element has incorrectly written getInitalState function. It should be something like this:

var GenerateRecipeFromList= React.createClass({
    getInitialState: function(){
      // Data to display if local storage is empty
      const defaultData = [
          'Spaghetti', 
          'pasta', 
          'oil', 
          'sauce', 
          'cheese'];
      
      // Get data from local storage
      const localData = JSON.parse(localStorage.getItem('spaghetti'));
      
      return {
        // if local storage is empty use default data
        spaghetti: localData ? localData : defaultData
      }
    },
    render: function(){
      // Sat current state to local storage
      localStorage.setItem('spaghetti', JSON.stringify(this.state.spaghetti));
      return(
        <div>
        <span>{this.state.spaghetti}</span>
        <button type="button"  id="btnAdd">Add a Recipe</button>
        </div>
      );
    }
  });

Here is codepen version: