Skip to content

Commit 2c90345

Browse files
committed
Add useReducer
1 parent 5a8f346 commit 2c90345

File tree

5 files changed

+62
-0
lines changed

5 files changed

+62
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<script>
2+
</script>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import type { PageLoad } from "./$types"
2+
3+
export const load = (async ({ params }) => {
4+
return {
5+
title: "useReducer",
6+
react: (await import("./react.jsx?raw")).default,
7+
svelte: (await import("./svelte.svelte?raw")).default,
8+
}
9+
}) satisfies PageLoad
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import React, { useReducer } from 'react'
2+
3+
const initialState = { count: 0 }
4+
5+
function reducer(state, action) {
6+
switch (action.type) {
7+
case 'increment':
8+
return { count: state.count + 1 }
9+
case 'decrement':
10+
return { count: state.count - 1 }
11+
default:
12+
throw new Error()
13+
}
14+
}
15+
16+
export default function Counter() {
17+
const [state, dispatch] = useReducer(reducer, initialState)
18+
return (
19+
<>
20+
Count: {state.count}
21+
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
22+
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
23+
</>
24+
)
25+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<script>
2+
import { writable } from "svelte/store"
3+
4+
const initialValue = 0
5+
const count = writable(initialValue)
6+
7+
count.increment = () => {
8+
count.update((state) => state + 1)
9+
}
10+
count.decrement = () => {
11+
count.update((state) => state - 1)
12+
}
13+
</script>
14+
15+
Count: {$count}
16+
<button on:click={count.decrement}>-</button>
17+
<button on:click={count.increment}>+</button>

src/routes/+layout.svelte

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
let tile2Url = "/useEffect"
1212
let tile3Url = "/useMemo"
1313
let tile4Url = "/useRef"
14+
let tile5Url = "/useReducer"
1415
</script>
1516

1617
<!-- App Shell -->
@@ -79,6 +80,14 @@
7980
href={tile4Url}
8081
class={tile4Url === $page.url.pathname ? "bg-primary-500" : ""}><Icon icon="code" /></AppRailTile
8182
>
83+
<AppRailTile
84+
label="useReducer"
85+
title="useReducer"
86+
value={4}
87+
tag="a"
88+
href={tile5Url}
89+
class={tile5Url === $page.url.pathname ? "bg-primary-500" : ""}><Icon icon="code" /></AppRailTile
90+
>
8291
</svelte:fragment>
8392

8493
<svelte:fragment slot="trail">

0 commit comments

Comments
 (0)