Skip to content

Commit

Permalink
Preact: support ssrSnapshot argument.
Browse files Browse the repository at this point in the history
  • Loading branch information
molefrog committed May 15, 2023
1 parent a18ff1c commit 72ac9b8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@
"jest": "^27.3.1",
"jest-esm-jsx-transform": "^1.0.0",
"preact": "^10.0.0",
"preact-render-to-string": "^6.0.3",
"prettier": "^2.4.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand Down
11 changes: 10 additions & 1 deletion preact/react-deps.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,20 @@ export {
useContext,
} from "preact/hooks";

// Copied from:
// https://github.com/facebook/react/blob/main/packages/shared/ExecutionEnvironment.js
const canUseDOM = !!(
typeof window !== "undefined" &&
typeof window.document !== "undefined" &&
typeof window.document.createElement !== "undefined"
);

// TODO: switch to `export { useSyncExternalStore } from "preact/compat"` once we update Preact to >= 10.11.3
function is(x, y) {
return (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y);
}
export function useSyncExternalStore(subscribe, getSnapshot) {
export function useSyncExternalStore(subscribe, getSnapshot, getSSRSnapshot) {
if (getSSRSnapshot && !canUseDOM) getSnapshot = getSSRSnapshot;
const value = getSnapshot();

const [{ _instance }, forceUpdate] = useState({
Expand Down
25 changes: 25 additions & 0 deletions test/preact-ssr.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @jsx h
* @jest-environment node
*/

import { h } from "preact";
import renderToString from "preact-render-to-string";

// make the library use Preact exports
jest.mock("../react-deps.js", () => require("../preact/react-deps.js"));
const { Route, Link, Switch, Router, useLocation } = require("../index.js");

describe("Preact SSR", () => {
it("supports SSR", () => {
const LocationPrinter = () => `location = ${useLocation()[0]}`;

const rendered = renderToString(
<Router ssrPath="/ssr/preact">
<LocationPrinter />
</Router>
);

expect(rendered).toBe("location = /ssr/preact");
});
});

0 comments on commit 72ac9b8

Please sign in to comment.