πŸ—„ React component to save data to localStorage on render phase safely
Clone or download
Latest commit 600c47f Nov 30, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src implement onSave prop (#8) Dec 1, 2018
.babelrc Initial commit Nov 24, 2018
.eslintrc Enhance test (#1) Nov 24, 2018
.gitignore Initial commit Nov 24, 2018
.prettierrc Initial commit Nov 24, 2018
.travis.yml add lint ci (#5) Nov 25, 2018
LICENSE Create LICENSE Nov 24, 2018
README.md implement onSave prop (#8) Dec 1, 2018
package.json bump 0.4.0 Dec 1, 2018
yarn.lock Enhance test (#1) Nov 24, 2018

README.md

react-save-localstorage

npm version Build Status

Save and sync your data on render phase to localStorage safely

Try it live at StackBlitz

import React, { Component } from 'react';
import SaveLocalStorage from 'react-save-localstorage';

class Home extends Component {
  state = {
    email: ''
  };
  render() {
    return (
      <div>
        {/* Mode 1: read only */}
        <SaveLocalStorage lsKey="lang">
          {lang => <div>Language: {lang || '-'}</div>}
        </SaveLocalStorage>

        {/* Mode 2: write only */}
        <SaveLocalStorage lsKey="emailBackup" value={this.state.email} />

        {/* Mode 3: dual */}
        <SaveLocalStorage value={this.state.email} lsKey="email">
          {v => (
            <div>
              <input
                value={v}
                onChange={e =>
                  this.setState({
                    email: e.target.value
                  })
                }
              />
              <div>Welcome, {v || 'Guest'}</div>
            </div>
          )}
        </SaveLocalStorage>
      </div>
    );
  }
}

Props

  • lsKey (string, required)

  • value (string)

  • sync (bool)

    To sync after value updates, default is true

  • children (func)

    Function that accept loaded value from localStorage

  • onSave (func)

    Function that accept object containing:

    • init (boolean that indicated it's the first mount)
    • value (the value being saved)

    This is called for every value updates.

License

MIT