UNPKG

use-history-state

Version:

`use-history-state` is replacement for `useState` that stores the state within the history state.

3 lines (2 loc) 1.03 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):t["use-history-state"]=e(t.React)}(this,function(t){var e=function(t,e){return void 0===e&&(e=window.history.state),e&&e[t]},n=function(t,e){return void 0===e&&(e=window.history.state),e&&t in e};return function(o,i){if(!i)throw new Error("Must provide a key");var r=t.useState(n(i)?e(i):o instanceof Function?o():o),s=r[0],a=r[1];t.useEffect(function(){var t=function(t){var o=t.state,r=e(i,o);n(i,o)&&r!==s&&a(r)};return window.addEventListener("popstate",t),function(){window.removeEventListener("popstate",t)}},[i,s]);var u=t.useCallback(function(t,e){var n,o,r;void 0===e&&(e=!1),r=t instanceof Function?t(s):t,a(r),e?window.history.replaceState(Object.assign({},window.history.state,((n={})[i]=r,n)),null):window.history.pushState(Object.assign({},window.history.state,((o={})[i]=r,o)),null)},[i,s]);return[s,u]}}); //# sourceMappingURL=useHistoryState.umd.js.map