use-history-state
Version:
`use-history-state` is replacement for `useState` that stores the state within the history state.
3 lines (2 loc) • 839 B
JavaScript
var t=require("react"),n=function(t,n){return void 0===n&&(n=window.history.state),n&&n[t]},e=function(t,n){return void 0===n&&(n=window.history.state),n&&t in n};module.exports=function(i,o){if(!o)throw new Error("Must provide a key");var r=t.useState(e(o)?n(o):i instanceof Function?i():i),s=r[0],a=r[1];t.useEffect(function(){var t=function(t){var i=t.state,r=n(o,i);e(o,i)&&r!==s&&a(r)};return window.addEventListener("popstate",t),function(){window.removeEventListener("popstate",t)}},[o,s]);var u=t.useCallback(function(t,n){var e,i,r;void 0===n&&(n=!1),r=t instanceof Function?t(s):t,a(r),n?window.history.replaceState(Object.assign({},window.history.state,((e={})[o]=r,e)),null):window.history.pushState(Object.assign({},window.history.state,((i={})[o]=r,i)),null)},[o,s]);return[s,u]};
//# sourceMappingURL=useHistoryState.js.map