|
1 | 1 | package react |
2 | 2 |
|
3 | | -import "github.com/gopherjs/gopherjs/js" |
| 3 | +import ( |
| 4 | + "github.com/gopherjs/gopherjs/js" |
| 5 | +) |
4 | 6 |
|
5 | 7 | type ( |
6 | 8 | // Node is a React node that can be displayed. |
@@ -31,7 +33,10 @@ type ( |
31 | 33 | // NOTE: `State[int]` should be `State[float64]` because of |
32 | 34 | // how the underlying React hook works. |
33 | 35 | // See: https://react.dev/reference/react/useState |
34 | | - State[T any] struct{ getter, setter *js.Object } |
| 36 | + State[T any] struct { |
| 37 | + initial T |
| 38 | + getter, setter *js.Object |
| 39 | + } |
35 | 40 |
|
36 | 41 | // ComponentFunc is a function that defines a React component. |
37 | 42 | // It takes props as input and returns a React element. |
@@ -109,21 +114,33 @@ func Button(value string, props Props, onClick func(e *js.Object)) *Element { |
109 | 114 | return CreateElement(`input`, props) |
110 | 115 | } |
111 | 116 |
|
112 | | -func UseState[T any](initial T) *State[T] { |
113 | | - s := react().Call(`useState`, initial) |
114 | | - return &State[T]{getter: s.Index(0), setter: s.Index(1)} |
| 117 | +func NewState[T any](initial T) *State[T] { |
| 118 | + return &State[T]{initial: initial} |
| 119 | +} |
| 120 | + |
| 121 | +func (s *State[T]) Use() { |
| 122 | + r := react().Call(`useState`, s.initial) |
| 123 | + s.getter = r.Index(0) |
| 124 | + s.setter = r.Index(1) |
115 | 125 | } |
116 | 126 |
|
117 | | -func (s *State[T]) Get() (zero T) { |
118 | | - if s != nil && s.getter != nil { |
119 | | - return s.getter.Interface().(T) |
| 127 | +func (s *State[T]) Get() (v T) { |
| 128 | + if s != nil { |
| 129 | + if s.getter != nil { |
| 130 | + return s.getter.Interface().(T) |
| 131 | + } |
| 132 | + return s.initial |
120 | 133 | } |
121 | 134 | return |
122 | 135 | } |
123 | 136 |
|
124 | 137 | func (s *State[T]) Set(v T) { |
125 | | - if s != nil && s.setter != nil { |
126 | | - s.setter.Invoke(v) |
| 138 | + if s != nil { |
| 139 | + if s.setter != nil { |
| 140 | + s.setter.Invoke(v) |
| 141 | + return |
| 142 | + } |
| 143 | + s.initial = v |
127 | 144 | } |
128 | 145 | } |
129 | 146 |
|
|
0 commit comments