feat: support passing signals as island props (#757)

This commit adds support for passing signals to islands in component
props. This is useful for passing around mutable state between islands.
The signal's value needs to be serializable for this to work.
This commit is contained in:
Luca Casonato
2023-05-31 10:29:46 +02:00
committed by GitHub
parent a6852fa58f
commit e3f9a0df08
11 changed files with 136 additions and 13 deletions
+3 -1
View File
@@ -3,6 +3,8 @@
"$fresh/": "../",
"preact": "https://esm.sh/preact@10.13.1",
"preact/": "https://esm.sh/preact@10.13.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@5.2.6"
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@5.2.6",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.3",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3"
}
}
+5 -6
View File
@@ -1,19 +1,18 @@
import { useState } from "preact/hooks";
import { Signal } from "@preact/signals";
import { IS_BROWSER } from "$fresh/runtime.ts";
interface CounterProps {
start: number;
count: Signal<number>;
}
export default function Counter(props: CounterProps) {
const [count, setCount] = useState(props.start);
export default function Counter({ count }: CounterProps) {
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count - 1)} disabled={!IS_BROWSER}>
<button onClick={() => count.value -= 1} disabled={!IS_BROWSER}>
-1
</button>
<button onClick={() => setCount(count + 1)} disabled={!IS_BROWSER}>
<button onClick={() => count.value += 1} disabled={!IS_BROWSER}>
+1
</button>
</div>
+5 -1
View File
@@ -1,13 +1,17 @@
import { useSignal } from "@preact/signals";
import Counter from "../islands/Counter.tsx";
export default function Home() {
const count = useSignal(3);
return (
<div>
<p>
Welcome to Fresh. Try to update this message in the ./routes/index.tsx
file, and refresh.
</p>
<Counter start={3} />
<Counter count={count} />
<Counter count={count} />
<Counter count={count} />
</div>
);
}