Skip to content

🗄 React component to save data to localStorage on render phase safely

License

Notifications You must be signed in to change notification settings

antonybudianto/react-save-localstorage

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

🗄 React component to save data to localStorage on render phase safely

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published