Skip to content

Commit

Permalink
add the methods and From impls (#3519)
Browse files Browse the repository at this point in the history
  • Loading branch information
its-the-shrimp committed Nov 5, 2023
1 parent 00a6183 commit 8d2cfde
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
28 changes: 28 additions & 0 deletions packages/yew/src/functional/hooks/use_reducer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use std::ops::Deref;
use std::rc::Rc;

use crate::functional::{hook, Hook, HookContext};
use crate::html::IntoPropValue;
use crate::Callback;

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

Expand Down Expand Up @@ -133,6 +135,24 @@ where
}
}

impl<T> From<UseReducerDispatcher<T>> for Callback<<T as Reducible>::Action>
where
T: Reducible,
{
fn from(val: UseReducerDispatcher<T>) -> Self {
Callback { cb: val.dispatch }
}
}

impl<T> IntoPropValue<Callback<<T as Reducible>::Action>> for UseReducerDispatcher<T>
where
T: Reducible,
{
fn into_prop_value(self) -> Callback<<T as Reducible>::Action> {
Callback { cb: self.dispatch }
}
}

impl<T> UseReducerDispatcher<T>
where
T: Reducible,
Expand All @@ -141,6 +161,14 @@ where
pub fn dispatch(&self, value: T::Action) {
(self.dispatch)(value)
}

/// Get a callback, invoking which is equivalent to calling `dispatch()`
/// on this same dispatcher.
pub fn to_callback(&self) -> Callback<<T as Reducible>::Action> {
Callback {
cb: self.dispatch.clone(),
}
}
}

/// The base function of [`use_reducer`] and [`use_reducer_eq`]
Expand Down
20 changes: 20 additions & 0 deletions packages/yew/src/functional/hooks/use_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use std::rc::Rc;

use super::{use_reducer, use_reducer_eq, Reducible, UseReducerDispatcher, UseReducerHandle};
use crate::functional::hook;
use crate::html::IntoPropValue;
use crate::Callback;

struct UseStateReducer<T> {
value: T,
Expand Down Expand Up @@ -171,6 +173,18 @@ where
}
}

impl<T> From<UseStateSetter<T>> for Callback<T> {
fn from(value: UseStateSetter<T>) -> Self {
Self::from(value.inner)
}
}

impl<T> IntoPropValue<Callback<T>> for UseStateSetter<T> {
fn into_prop_value(self) -> Callback<T> {
self.inner.into_prop_value()
}
}

impl<T> PartialEq for UseStateSetter<T> {
fn eq(&self, rhs: &Self) -> bool {
self.inner == rhs.inner
Expand All @@ -182,4 +196,10 @@ impl<T> UseStateSetter<T> {
pub fn set(&self, value: T) {
self.inner.dispatch(value)
}

/// Get a callback, invoking which is equivalent to calling `set()`
/// on this same setter.
pub fn to_callback(&self) -> Callback<T> {
self.inner.to_callback()
}
}

0 comments on commit 8d2cfde

Please sign in to comment.