UNPKG

@bigfishtv/cockpit

Version:

51 lines (43 loc) 1.49 kB
/** * @module Decorators/persistState */ import React, { Component } from 'react' const localStorageEnabled = typeof Storage !== 'undefined' /** * Decorator that exposes persists state by exposing a persist prop * @param {Object} defaultState * @param {Function} getPersistKey - function for getting which localStorage key to use * @return {component} returns wrapped component */ export default function wrapComponentWithPersistentState(defaultState = {}, getPersistKey = () => false) { return function(WrappedComponent) { return class PersistentStateDecorator extends Component { constructor(props) { super(props) this.persistKey = props.persistKey || getPersistKey(props) this.state = this.restoreFromLocalStorage(defaultState) } persist = state => { this.setState(state, () => { this.saveToLocalStorage() }) } saveToLocalStorage() { if (!localStorageEnabled || !this.persistKey) return localStorage.setItem(this.persistKey, JSON.stringify(this.state)) } restoreFromLocalStorage(defaultState = {}) { if (!localStorageEnabled || !this.persistKey) return defaultState if (localStorage[this.persistKey]) { return JSON.parse(localStorage.getItem(this.persistKey)) } else { localStorage.setItem(this.persistKey, JSON.stringify(defaultState)) return defaultState } } render() { return <WrappedComponent persist={this.persist} {...this.props} {...this.state} /> } } } }