Skip to content

Commit

Permalink
refactoring sandbox/csr Store example
Browse files Browse the repository at this point in the history
  • Loading branch information
LankyMoose committed Oct 2, 2024
1 parent fe5d85d commit 31f2e4d
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 63 deletions.
63 changes: 0 additions & 63 deletions sandbox/csr/src/components/StoreExample.tsx

This file was deleted.

36 changes: 36 additions & 0 deletions sandbox/csr/src/components/StoreExample/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { useTodosStore, TodoItem as TodoItemType } from "./store"

export function StoreExample() {
const { value: todos } = useTodosStore(
(store) => store,
(prev, next) => prev.length === next.length
)
console.log("parent component")

return (
<ul>
{todos.map((todo) => (
<TodoItem todo={todo} />
))}
</ul>
)
}

function TodoItem({ todo }: { todo: TodoItemType }) {
const { toggleTodo } = useTodosStore((store) =>
store.find((item) => item.id === todo.id)
)

console.log("child component", todo.id)

return (
<div>
{todo.text}
<input
type="checkbox"
checked={todo.done}
onchange={() => toggleTodo(todo.id)}
/>
</div>
)
}
28 changes: 28 additions & 0 deletions sandbox/csr/src/components/StoreExample/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { createStore } from "kaioken"

export type TodoItem = {
id: string
text: string
done?: boolean
}

export const useTodosStore = createStore(
[
{ id: "d70649dc-7b13-431a-8377-fc0ce31801ac", text: "buy coffee" },
{ id: "83d55e40-c0e7-438e-96df-fe661fd0bcec", text: "walk the dog" },
{ id: "d5c1d2d8-8f8b-4b0e-8e0c-6f6c7e8e8e8e", text: "use the whip" },
] as TodoItem[],
function (set) {
return {
addTodo: (text: string) =>
set((prev) => [...prev, { id: crypto.randomUUID(), text }]),

toggleTodo: (id: string) =>
set((prev) =>
prev.map((item) =>
item.id === id ? { ...item, done: !item.done } : item
)
),
}
}
)

0 comments on commit 31f2e4d

Please sign in to comment.