Skip to content

Commit

Permalink
useUrl hook for router (#338)
Browse files Browse the repository at this point in the history
* useUrl hook for router

* useLayoutEffect0
  • Loading branch information
rickyvetter committed Feb 19, 2019
2 parents 9758d49 + 4b3b228 commit 0591ee2
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
19 changes: 18 additions & 1 deletion lib/js/src/ReasonReact.js
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,22 @@ function unwatchUrl(watcherID) {
}
}

function useUrl() {
var match = React.useState(url);
var setUrl = match[1];
React.useLayoutEffect((function () {
var watcherId = watchUrl((function (url) {
return Curry._1(setUrl, (function () {
return url;
}));
}));
return (function () {
return unwatchUrl(watcherId);
});
}), ([]));
return match[0];
}

function useRecordApi(componentSpec) {
var initialState = React.useMemo(componentSpec[/* initialState */10], ([]));
var unmountSideEffects = React.useRef(/* array */[]);
Expand Down Expand Up @@ -647,7 +663,8 @@ var Router = [
replace,
watchUrl,
unwatchUrl,
url
url,
useUrl
];

exports.statelessComponent = statelessComponent;
Expand Down
11 changes: 11 additions & 0 deletions src/ReasonReact.re
Original file line number Diff line number Diff line change
Expand Up @@ -883,6 +883,17 @@ module Router = {
| Some((window: Dom.window)) =>
removeEventListener(window, "popstate", watcherID)
};

let useUrl = () => {
let (url, setUrl) = React.useState(dangerouslyGetInitialUrl);

React.useLayoutEffect0(() => {
let watcherId = watchUrl(url => setUrl(_ => url));
Some(() => unwatchUrl(watcherId));
});

url;
};
};

type sidEffectualState('state, 'retainedProps, 'action) = {
Expand Down
2 changes: 2 additions & 0 deletions src/ReasonReact.rei
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,8 @@ module Router: {
for an example.
*/
let dangerouslyGetInitialUrl: unit => url;
/** hook for watching url changes */
let useUrl: unit => url;
};

[@bs.module "react"] external fragment: 'a = "Fragment";
Expand Down

0 comments on commit 0591ee2

Please sign in to comment.