Coder Social home page Coder Social logo

react-localstorage's Introduction

React-LocalStorage

Simply synchronize a component's state with localStorage, when available.

This is an old-style Mixin, which means it's probably compatible with your React application if it's a few years old. If you're a hip young programmer, you might prefer a hook, instead.

Install

React-LocalStorage

    npm i react-localstorage --save

Usage

A simple component:

const React = require('react');
const LocalStorageMixin = require('react-localstorage');
const reactMixin = require('react-mixin');

// This is all you need to do
@reactMixin.decorate(LocalStorageMixin)
class TestComponent extends React.Component {
  static displayName = 'TestComponent';

  state = {counter: 0};

  onClick() {
    this.setState({counter: this.state.counter + 1});
  }

  render() {
    return <span onClick={this.onClick}>{this.state.counter}</span>;
  }
}

Options

The key that state is serialized to under localStorage is chosen with the following code:

function getLocalStorageKey(component) {
  if (component.getLocalStorageKey) return component.getLocalStorageKey();
  if (component.props.localStorageKey === false) return false;
  if (typeof component.props.localStorageKey === 'function') return component.props.localStorageKey.call(component);
  return component.props.localStorageKey || getDisplayName(component) || 'react-localstorage';
}

If you are synchronizing multiple components with the same displayName to localStorage, you must set a unique localStorageKey prop on the component. You may set a function as well.

Alternatively, you may define the method getLocalStorageKey on the component's prototype. This gives you the freedom to choose keys depending on the component's props or state.

To disable usage of localStorage entirely, pass false or a function that evaluates to false.

Filtering

If you only want to save parts of state in localStorage, set stateFilterKeys to an array of strings corresponding to the state keys you want to save.

getDefaultProps: function() {
  return {
    stateFilterKeys: ['one', 'two']
  };
}

You can do this by setting a stateFilterKeys prop or define the method getStateFilterKeys on the component's prototype.

getStateFilterKeys: function() {
  return ['one', 'two'];
}

Server Rendering

LocalStorageMixin will call setState on componentDidMount, so it will not break server rendering checksums. This is new as of 0.2.0.

Tests

We use jest as the test runner. To run the test, simply yarn install all the dependencies and run yarn test.

react-localstorage's People

Contributors

dependabot[bot] avatar hongymagic avatar multivoltage avatar possibilities avatar salehhamadeh avatar shantp avatar ssnau avatar strml avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-localstorage's Issues

Usage

Using this module. When or how do I go about checking if the data is stale?

I'm using localstorage to store results from an api request. If a user returns to the app at a future date the info from localstorage must be checked for staleness and initiate another request to the api for fresh data.

Localstorage with valueLink={this.linkState('email')} gives an error

I am trying to use localstorage in an reactClass that also contains an form with valueLink attritbute.

This generates the following error:

Error: Invariant Violation: While component Login was saving state to localStorage, the localStorage entry was modified by another actor. This can happen when multiple components are using the same localStorage key. Set the property localStorageKey on Login.

Snippet of the code.

var Login = React.createClass({
     displayName: 'Login', //Localstorage
     mixins: [LocalStorageMixin],


    submit: function(e) {
        e.preventDefault();
        User.Actions.login(this.state.email, this.state.password);
    },

    render: function() {
        var stack = this.state.form.error;

        if(this.state.form.success == true) {
            return (<div>
                        <h2>Inloggen</h2>
                        U bent nu aangemeld.
                    </div>
                    )
        } else

        return(
                <div>
                    <h2>Inloggen</h2>
                    <form>
                        <div >
                            <label htmlFor="email">Email</label>
                            <input type    ="email" valueLink={this.linkState('email')} className="form-control" id="email" placeholder="Email" />
                        </div>
                        <div >
                            <label htmlFor="pwd">Wachtwoord</label>
                            <input type    ="password" valueLink={this.linkState('password')} className="form-control" id="pwd" placeholder="Wachtwoord" />
                        </div>

                         <div className="form-group">
                            <div >
                              <button type="submit" className="btn btn-default" onClick={this.submit}>Inloggen</button>
                            </div>
                          </div>


                    </form>
                </div>
            );

    }

}); module.exports = Login;

Cant use it as es6 component

i try to use is in es6 component and my code looks like this:
class TestComponent extends Component{

constructor(props) {
super(props);

this.displayName = 'TestComponent';
this.mixins = [LocalStorageMixin];

this.state = {
  counter:0,
};

this.onClick = this.onClick.bind(this);

}

onClick() {
this.setState({
counter: this.state.counter + 1}
);
}

render() {
return (
{this.state.counter}
);
}
};

but the state dont stay when i refrash the page... - note that if i use is at regular createclass thats work...

Should store at a different key if this.props.localStorageKey

I can create a jsbin or something to demonstrate, but it appears that if the localStorageKey prop changes that it doesn't begin loading/saving to the new key.

If I'm understanding the code correctly, it not be too hard like adding a componentWillReceiveProps that reruns this.componentDidMount? I'll try to play around with this when I get a chance, but wanted to bring it up here in case you've seen this before.

it would be awesome if Dates were automatically de-serialized

Part of my state is Dates.
I have date-pickers that need those dates in the state.
When my state is saved and restored, my dates have become strings.

It would be awesome if (somehow) those dates were restored as dates.
( for extra bonus points, also make regexes automatically serialize/deserialize -- I also have one of those in my state )

In the meantime, where should I write code to de-serialize my dates?
Is there a hook?...that is called after (or during) every de-serialize?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.