Skip to content

Commit 8d2cfde

Browse files
add the methods and From impls (#3519)
1 parent 00a6183 commit 8d2cfde

2 files changed

Lines changed: 48 additions & 0 deletions

File tree

packages/yew/src/functional/hooks/use_reducer.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ use std::ops::Deref;
55
use std::rc::Rc;
66

77
use crate::functional::{hook, Hook, HookContext};
8+
use crate::html::IntoPropValue;
9+
use crate::Callback;
810

911
type DispatchFn<T> = Rc<dyn Fn(<T as Reducible>::Action)>;
1012

@@ -133,6 +135,24 @@ where
133135
}
134136
}
135137

138+
impl<T> From<UseReducerDispatcher<T>> for Callback<<T as Reducible>::Action>
139+
where
140+
T: Reducible,
141+
{
142+
fn from(val: UseReducerDispatcher<T>) -> Self {
143+
Callback { cb: val.dispatch }
144+
}
145+
}
146+
147+
impl<T> IntoPropValue<Callback<<T as Reducible>::Action>> for UseReducerDispatcher<T>
148+
where
149+
T: Reducible,
150+
{
151+
fn into_prop_value(self) -> Callback<<T as Reducible>::Action> {
152+
Callback { cb: self.dispatch }
153+
}
154+
}
155+
136156
impl<T> UseReducerDispatcher<T>
137157
where
138158
T: Reducible,
@@ -141,6 +161,14 @@ where
141161
pub fn dispatch(&self, value: T::Action) {
142162
(self.dispatch)(value)
143163
}
164+
165+
/// Get a callback, invoking which is equivalent to calling `dispatch()`
166+
/// on this same dispatcher.
167+
pub fn to_callback(&self) -> Callback<<T as Reducible>::Action> {
168+
Callback {
169+
cb: self.dispatch.clone(),
170+
}
171+
}
144172
}
145173

146174
/// The base function of [`use_reducer`] and [`use_reducer_eq`]

packages/yew/src/functional/hooks/use_state.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ use std::rc::Rc;
44

55
use super::{use_reducer, use_reducer_eq, Reducible, UseReducerDispatcher, UseReducerHandle};
66
use crate::functional::hook;
7+
use crate::html::IntoPropValue;
8+
use crate::Callback;
79

810
struct UseStateReducer<T> {
911
value: T,
@@ -171,6 +173,18 @@ where
171173
}
172174
}
173175

176+
impl<T> From<UseStateSetter<T>> for Callback<T> {
177+
fn from(value: UseStateSetter<T>) -> Self {
178+
Self::from(value.inner)
179+
}
180+
}
181+
182+
impl<T> IntoPropValue<Callback<T>> for UseStateSetter<T> {
183+
fn into_prop_value(self) -> Callback<T> {
184+
self.inner.into_prop_value()
185+
}
186+
}
187+
174188
impl<T> PartialEq for UseStateSetter<T> {
175189
fn eq(&self, rhs: &Self) -> bool {
176190
self.inner == rhs.inner
@@ -182,4 +196,10 @@ impl<T> UseStateSetter<T> {
182196
pub fn set(&self, value: T) {
183197
self.inner.dispatch(value)
184198
}
199+
200+
/// Get a callback, invoking which is equivalent to calling `set()`
201+
/// on this same setter.
202+
pub fn to_callback(&self) -> Callback<T> {
203+
self.inner.to_callback()
204+
}
185205
}

0 commit comments

Comments
 (0)