From 331d85d3a2d56186b21a03722953ccac9935daaa Mon Sep 17 00:00:00 2001 From: Tom Hacohen Date: Sat, 16 Dec 2017 20:29:50 +0000 Subject: [PATCH] history persistor: follow the recommended HOC guidelines. --- src/Journal/JournalCalendar.tsx | 2 +- src/Pim/PimMain.tsx | 4 ++-- src/persist-state-history.tsx | 38 +++++++++++++++++---------------- 3 files changed, 23 insertions(+), 21 deletions(-) diff --git a/src/Journal/JournalCalendar.tsx b/src/Journal/JournalCalendar.tsx index 1941427..d36de46 100644 --- a/src/Journal/JournalCalendar.tsx +++ b/src/Journal/JournalCalendar.tsx @@ -36,7 +36,7 @@ class JournalCalendar extends React.PureComponent { } render() { - const PersistCalendar = historyPersistor(Calendar, 'Calendar'); + const PersistCalendar = historyPersistor('Calendar')(Calendar); let items = this.props.entries; return ( diff --git a/src/Pim/PimMain.tsx b/src/Pim/PimMain.tsx index 858c1d3..32460f1 100644 --- a/src/Pim/PimMain.tsx +++ b/src/Pim/PimMain.tsx @@ -77,7 +77,7 @@ class PimMain extends React.PureComponent { } as any, }; - const PersistCalendar = historyPersistor(Calendar, 'Calendar'); + const PersistCalendar = historyPersistor('Calendar')(Calendar); return ( @@ -114,4 +114,4 @@ class PimMain extends React.PureComponent { } } -export default historyPersistor(PimMain, 'PimMain'); +export default historyPersistor('PimMain')(PimMain); diff --git a/src/persist-state-history.tsx b/src/persist-state-history.tsx index 8e54913..5f8cba5 100644 --- a/src/persist-state-history.tsx +++ b/src/persist-state-history.tsx @@ -6,26 +6,28 @@ let stateCache = {}; type Constructor = new(...args: any[]) => T; -export function historyPersistor>(Base: T, tag: string) { - return withRouter(class extends Base { - constructor(...rest: any[]) { - const props = rest[0]; - super(...rest); - const tagName = this.getKeyForTag(props, tag); - if (tagName in stateCache) { - this.state = stateCache[tagName]; +export function historyPersistor(tag: string) { + return function>(Base: T) { + return withRouter(class extends Base { + constructor(...rest: any[]) { + const props = rest[0]; + super(...rest); + const tagName = this.getKeyForTag(props, tag); + if (tagName in stateCache) { + this.state = stateCache[tagName]; + } } - } - componentWillUnmount() { - if (super.componentWillUnmount) { - super.componentWillUnmount(); + componentWillUnmount() { + if (super.componentWillUnmount) { + super.componentWillUnmount(); + } + stateCache[this.getKeyForTag(this.props, tag)] = this.state; } - stateCache[this.getKeyForTag(this.props, tag)] = this.state; - } - getKeyForTag(props: any, tagName: string) { - return props.location.pathname + ':' + tagName; - } - }); + getKeyForTag(props: any, tagName: string) { + return props.location.pathname + ':' + tagName; + } + }); + }; }