File tree Expand file tree Collapse file tree 3 files changed +67
-1
lines changed
components/usesyncexternalstore
domain/usesyncexternalstore
pages/usesyncexternalstore Expand file tree Collapse file tree 3 files changed +67
-1
lines changed Original file line number Diff line number Diff line change 11import Page from '@/common/layout/page'
2+ import useTodos from '@/domain/usesyncexternalstore/todostore'
23
34function UseSyncExternalStoreComponent ( ) {
5+ const { todos, add } = useTodos ( )
6+
47 return (
58 < Page >
69 < h2 >
710 UseSyncExternalStoreComponent
811 </ h2 >
12+
13+ { ( todos !== undefined ) &&
14+ < div >
15+ < ul >
16+ { todos . map ( ( item , index ) => (
17+ < li key = { index } > { item . text } </ li >
18+ ) ) }
19+ </ ul >
20+ </ div >
21+ }
22+
23+ < button onClick = { ( ) => add ( ) } > Add Todo</ button >
924 </ Page >
1025 )
1126}
Original file line number Diff line number Diff line change 1+ import { useSyncExternalStore } from 'react'
2+
3+ // https://react.dev/reference/react/useSyncExternalStore
4+
5+ let nextId = 0
6+ let todos = [ { id : nextId ++ , text : 'Todo #1' } ]
7+ let listeners = [ ]
8+
9+ export default function useTodos ( ) {
10+ const todos = useSyncExternalStore (
11+ todoStore . subscribe ,
12+ todoStore . getSnapshot ,
13+ todoStore . getServerSnapshot
14+ )
15+
16+ return {
17+ todos,
18+ add : todoStore . addTodo
19+ }
20+ }
21+
22+ export const todoStore = {
23+ addTodo ( ) {
24+ todos = [ ...todos , { id : nextId ++ , text : 'Todo #' + nextId } ]
25+ emitChange ( )
26+ } ,
27+
28+ subscribe ( listener ) {
29+ listeners = [ ...listeners , listener ]
30+
31+ return ( ) => {
32+ listeners = listeners . filter ( item => item !== listener )
33+ }
34+ } ,
35+
36+ getSnapshot ( ) {
37+ return todos
38+ } ,
39+
40+ getServerSnapshot ( ) {
41+ return todos
42+ }
43+ }
44+
45+ function emitChange ( ) {
46+ for ( let listener of listeners ) {
47+ listener ( )
48+ }
49+ }
Original file line number Diff line number Diff line change 11import UseSyncExternalStoreComponent from '@/components/usesyncexternalstore'
22
33function UseSyncExternalStore ( ) {
4- return ( < UseSyncExternalStoreComponent /> )
4+ return (
5+ < UseSyncExternalStoreComponent />
6+ )
57}
68
79export default UseSyncExternalStore
You can’t perform that action at this time.
0 commit comments