Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to localstorage in react.js

I'm having a problem with a component that gets data from an array in localstorage. It gets the initial data when the page loads, but how do I update when localstorage is changed?

import React, {Component} from 'react'; 
    class MovieList extends Component {
       constructor(props){
          super(props)
            this.state = {
            filmList: []     
          }
       }    
      componentWillMount(){
          var film = [],
          keys = Object.keys(localStorage),
          i = keys.length;
          while ( i-- ) {
             film.push( localStorage.getItem(keys[i]))     
          }
          this.setState({filmList: film})

      };

      render(){
        return(
           <ul>
              <li>{this.state.filmlist}</li>            
           </ul>

        );
    }

}

export default MovieList;
like image 348
jermain joseph Avatar asked Apr 10 '17 00:04

jermain joseph


People also ask

How to use localStorage with react?

Using localStorage with React is really simple. Just find out what are the best moments to save and get back your data. This will change from component to component. Generally speaking, you can rehydrate your component both in the constructor and in the componentDidMountlifecycle method.

What is localStorage in Salesforce?

LocalStorage is a web storage object to store the data on the user’s computer locally, which means the stored data is saved across browser sessions and the data stored has no expiration time.

Why can't I access localStorage through localStorage?

I would've added a code snippet for you to run but you can't access localStorage through it due to cross-origin issues.

How do I remove items from localStorage in Node JS?

App.jsx In the above example, when the Done button is clicked, the handle function is executed which will set the items in the localStorage of the user and display it. But when the Remove button is clicked, the remove function is executed which will remove the items from the localStorage.


2 Answers

Per Mozilla's Web API docs there's a StorageEvent that gets fired whenever a change is made to the Storage object.

I created an Alert component within my application that would go off whenever a change was made to a specific localStorage item. I would've added a code snippet for you to run but you can't access localStorage through it due to cross-origin issues.

class Alert extends React.Component {
    constructor(props) {
        super(props)
        this.agree = this.agree.bind(this)
        this.disagree = this.disagree.bind(this)
        this.localStorageUpdated = this.localStorageUpdated.bind(this)
        this.state = {
            status: null
        }
    }
    componentDidMount() {
        if (typeof window !== 'undefined') {
            this.setState({status: localStorage.getItem('localstorage-status') ? true : false})

            window.addEventListener('storage', this.localStorageUpdated)
        }
    }
    componentWillUnmount(){
        if (typeof window !== 'undefined') {
            window.removeEventListener('storage', this.localStorageUpdated)
        }
    }
    agree(){
        localStorage.setItem('localstorage-status', true)
        this.updateState(true)
    }
    disagree(){
        localStorage.setItem('localstorage-status', false)
        this.updateState(false)
    }
    localStorageUpdated(){
        if (!localStorage.getItem('localstorage-status')) {
            this.updateState(false)
        } 
        else if (!this.state.status) {
            this.updateState(true)
        }
    }
    updateState(value){
        this.setState({status:value})
    }
    render () {
        return( !this.state.status ? 
            <div class="alert-wrapper">
                <h3>The Good Stuff</h3>
                <p>Blah blah blah</p>
                <div class="alert-button-wrap">
                    <button onClick={this.disagree}>Disagree</button>
                    <button onClick={this.agree}>Agree</button>
                </div>
            </div>
         : null )
    }
}
like image 73
Josh Valdivieso Avatar answered Oct 13 '22 05:10

Josh Valdivieso


For anyone stumbling upon this question, the answer to "how to listen to localStorage changes" can be found here: https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent

like image 42
mezod Avatar answered Oct 13 '22 04:10

mezod