2

CODE:

var React = require('react');
var Recipe = require('./Recipe.jsx');
var AddRecipe = require('./AddRecipe.jsx');
var EditRecipe = require('./EditRecipe.jsx');

var RecipeBox = React.createClass({


    getInitialState: function () {
        return {
           recipesArray: [],
           adding: false,
           editing: false,
           currentIndex: 0
        };
    },

    handleClick: function () {
        this.setState({
            adding: true
        }); 
    },
    handleEditClick: function(index) {
        this.setState({
            editing: true,
            currentIndex: index
        }); 
    },
    handleDeleteClick: function(index) {
        var newRecipesArray = this.state.recipesArray;
        newRecipesArray.splice(index-1,1);
        this.setState({
            recipesArray: newRecipesArray
        });
    },
    handleClose: function() {
        this.setState({
            adding: false,
            editing: false
        });
    },
    handleAdd: function(newRecipe) {
        this.setState({
            recipesArray: this.state.recipesArray.concat(newRecipe)
        });
    },
    handleEdit: function(newRecipe, index) {
        var newRecipesArray = this.state.recipesArray;
        newRecipesArray[index-1] = newRecipe;
        this.setState({
            recipesArray: newRecipesArray
        });

    },

    render: function() {
        var i = 0;
        var that = this;

        var recipes = this.state.recipesArray.map(function(item) {
            i++
            return (
                <div key={"div"+i} className="table">
                    <Recipe key={i} name={item.name} ingredients={item.ingredients} />
                    <button key ={"edit"+i} onClick={() => { that.handleEditClick(i)}} className="btn edit btn-primary">Edit</button>
                    <button  key ={"delete"+i} onClick={() => { that.handleDeleteClick(i)}} className="btn delete btn-danger">Delete</button>
                </div>
            );
        });

        return (
            <div>
                <h1>React.js Recipe Box</h1>
                <button className="btn btn-primary" onClick={this.handleClick}>Add Recipe</button>
                <table>
                    <tbody>
                        <tr>
                            <th>RECIPES</th>
                        </tr>
                    </tbody>
                </table>
                {recipes}
                { this.state.adding ? <AddRecipe handleClose={this.handleClose}  handleAdd={this.handleAdd} /> : null }
                { this.state.editing ? <EditRecipe currentIndex = {this.state.currentIndex} handleClose={this.handleClose}  handleEdit={this.handleEdit}/> : null }
            </div>
        );
    },
});

module.exports = RecipeBox;

QUESTION:

How should I implement saving state to localStorage ? What would be the most elegant implementation ?

Currently learning React and looking to write clean and elegant code.

Julian
  • 33,915
  • 22
  • 119
  • 174
Coder1000
  • 4,071
  • 9
  • 35
  • 84
  • Why the downvote ? I am willing to edit my question if necessary. Please explain. – Coder1000 Apr 18 '17 at 19:10
  • 1
    They down voted because, you really didn't say what you tried. You put your code in but didn't put what you tried for local storage or any issues that you were having. In general you will get down voted for that. – webdad3 Apr 18 '17 at 19:16
  • @webdad3 Makes sense. – Coder1000 Apr 19 '17 at 14:22

2 Answers2

2

Whenever an update to state is fired, it will trigger the lifecycle method of componentDidUpdate. You can hook into that method in order to save the state of the component.

componentDidUpdate() {
  window.localStorage.setItem('state', JSON.stringify(this.state));
}

Depending on your use case, you should be able to load it back up on componentDidMount.

componentDidMount() {
  // there is a chance the item does not exist
  // or the json fails to parse
  try {
    const state = window.localStorage.getItem('state');
    this.setState({ ...JSON.parse(state) });
  } catch (e) {}
}

I would warn you, you probably want a solution more like redux with a localStorage adapter for a "full-fledged" solution. This one is pretty frail in a few different ways.

corvid
  • 10,733
  • 11
  • 61
  • 130
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Apr 18 '17 at 20:14
0

I would take a look at plugins that make localstorage easier (not browser specific). An example would be this:

https://github.com/artberri/jquery-html5storage

The page above has all the information you need to get started. If that one doesn't work then I would continue to search. There are plenty out there. There may be newer ones that use React as well. The jQuery plugins have worked for me when I was learning/doing Angular.

webdad3
  • 8,893
  • 30
  • 121
  • 223