Coder1000
Coder1000

Reputation: 4461

How should I implement saving state to localStorage?

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.

Upvotes: 2

Views: 1441

Answers (2)

corvid
corvid

Reputation: 11187

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.

Upvotes: 2

webdad3
webdad3

Reputation: 9080

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.

Upvotes: 0

Related Questions