Struct freya::prelude::UseState

pub struct UseState<T>where
    T: 'static,{ /* private fields */ }

Implementations§

§

impl<T> UseState<T>where T: 'static,

pub fn set(&self, new: T)

Set the state to a new value.

pub fn current(&self) -> Rc<T>

Get the current value of the state by cloning its container Rc.

This is useful when you are dealing with state in async contexts but need to know the current value. You are not given a reference to the state.

Examples

An async context might need to know the current value:

fn component(cx: Scope) -> Element {
    let count = use_state(cx, || 0);
    cx.spawn({
        let set_count = count.to_owned();
        async move {
            let current = set_count.current();
        }
    })
}

pub fn setter(&self) -> Rc<dyn Fn(T)>

Get the setter function directly without the UseState wrapper.

This is useful for passing the setter function to other components.

However, for most cases, calling to_owned on the state is the preferred way to get “another” state handle.

Examples

A component might require an Rc<dyn Fn(T)> as an input to set a value.

fn component(cx: Scope) -> Element {
    let value = use_state(cx, || 0);

    rsx!{
        Component {
            handler: value.setter()
        }
    }
}

pub fn modify(&self, f: impl FnOnce(&T) -> T)

Set the state to a new value, using the current state value as a reference.

This is similar to passing a closure to React’s set_value function.

Examples

Basic usage:

fn component(cx: Scope) -> Element {
    let value = use_state(cx, || 0);

    // to increment the value
    value.modify(|v| v + 1);

    // usage in async
    cx.spawn({
        let value = value.to_owned();
        async move {
            value.modify(|v| v + 1);
        }
    });

}

pub fn get(&self) -> &T

Get the value of the state when this handle was created.

This method is useful when you want an Rc around the data to cheaply pass it around your app.

Warning

This will return a stale value if used within async contexts.

Try current to get the real current value of the state.

Example
fn component(cx: Scope) -> Element {
    let value = use_state(cx, || 0);

    let as_rc = value.get();
    assert_eq!(as_rc.as_ref(), &0);

}

pub fn get_rc(&self) -> &Rc<T>

pub fn needs_update(&self)

Mark the component that create this UseState as dirty, forcing it to re-render.

fn component(cx: Scope) -> Element {
    let count = use_state(cx, || 0);
    cx.spawn({
        let count = count.to_owned();
        async move {
            // for the component to re-render
            count.needs_update();
        }
    })
}
§

impl<T> UseState<T>where T: Clone,

pub fn with_mut(&self, apply: impl FnOnce(&mut T))

Get a mutable handle to the value by calling ToOwned::to_owned on the current value.

This is essentially cloning the underlying value and then setting it, giving you a mutable handle in the process. This method is intended for types that are cheaply cloneable.

If you are comfortable dealing with RefMut, then you can use make_mut to get the underlying slot. However, be careful with RefMut since you might panic if the RefCell is left open.

Examples
let val = use_state(cx, || 0);

val.with_mut(|v| *v = 1);

pub fn make_mut(&self) -> RefMut<'_, T>

Get a mutable handle to the value by calling ToOwned::to_owned on the current value.

This is essentially cloning the underlying value and then setting it, giving you a mutable handle in the process. This method is intended for types that are cheaply cloneable.

Warning

Be careful with RefMut since you might panic if the RefCell is left open!

Examples
let val = use_state(cx, || 0);

*val.make_mut() += 1;

pub fn split(&self) -> (&T, &UseState<T>)

Convert this handle to a tuple of the value and the handle itself.

Trait Implementations§

§

impl<T> Add<T> for &UseState<T>where T: Add + Copy,

§

type Output = <T as Add>::Output

The resulting type after applying the + operator.
§

fn add(self, other: T) -> <&UseState<T> as Add<T>>::Output

Performs the + operation. Read more
§

impl<T> AddAssign<T> for &UseState<T>where T: Add<Output = T> + Copy,

§

fn add_assign(&mut self, rhs: T)

Performs the += operation. Read more
§

impl<T> AddAssign<T> for UseState<T>where T: Add<Output = T> + Copy,

§

fn add_assign(&mut self, rhs: T)

Performs the += operation. Read more
§

impl<T> Binary for UseState<T>where T: Binary,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter.
§

impl<T> Clone for UseState<T>where T: 'static,

§

fn clone(&self) -> UseState<T>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<T> Debug for UseState<T>where T: Debug,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T> Deref for UseState<T>

§

type Target = T

The resulting type after dereferencing.
§

fn deref(&self) -> &<UseState<T> as Deref>::Target

Dereferences the value.
§

impl<T> Display for UseState<T>where T: 'static + Display,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T> Div<T> for &UseState<T>where T: Div + Copy,

§

type Output = <T as Div>::Output

The resulting type after applying the / operator.
§

fn div(self, other: T) -> <&UseState<T> as Div<T>>::Output

Performs the / operation. Read more
§

impl<T> DivAssign<T> for &UseState<T>where T: Div<Output = T> + Copy,

§

fn div_assign(&mut self, rhs: T)

Performs the /= operation. Read more
§

impl<T> DivAssign<T> for UseState<T>where T: Div<Output = T> + Copy,

§

fn div_assign(&mut self, rhs: T)

Performs the /= operation. Read more
§

impl<T> Mul<T> for &UseState<T>where T: Mul + Copy,

§

type Output = <T as Mul>::Output

The resulting type after applying the * operator.
§

fn mul(self, other: T) -> <&UseState<T> as Mul<T>>::Output

Performs the * operation. Read more
§

impl<T> MulAssign<T> for &UseState<T>where T: Mul<Output = T> + Copy,

§

fn mul_assign(&mut self, rhs: T)

Performs the *= operation. Read more
§

impl<T> MulAssign<T> for UseState<T>where T: Mul<Output = T> + Copy,

§

fn mul_assign(&mut self, rhs: T)

Performs the *= operation. Read more
§

impl<T> Not for &UseState<T>where T: Not + Copy,

§

type Output = <T as Not>::Output

The resulting type after applying the ! operator.
§

fn not(self) -> <&UseState<T> as Not>::Output

Performs the unary ! operation. Read more
§

impl<T> Not for UseState<T>where T: Not + Copy,

§

type Output = <T as Not>::Output

The resulting type after applying the ! operator.
§

fn not(self) -> <UseState<T> as Not>::Output

Performs the unary ! operation. Read more
§

impl<T> PartialEq<T> for UseState<T>where T: PartialEq,

§

fn eq(&self, other: &T) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl PartialEq<bool> for &UseState<bool>

§

fn eq(&self, other: &bool) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl<T> PartialEq for UseState<T>

§

fn eq(&self, other: &UseState<T>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl<T> PartialOrd<T> for UseState<T>where T: PartialOrd,

§

fn ge(&self, other: &T) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
§

fn gt(&self, other: &T) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
§

fn le(&self, other: &T) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
§

fn lt(&self, other: &T) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
§

fn partial_cmp(&self, other: &T) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
§

impl<T> PartialOrd for UseState<T>where T: PartialOrd,

§

fn ge(&self, other: &UseState<T>) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
§

fn gt(&self, other: &UseState<T>) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
§

fn le(&self, other: &UseState<T>) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
§

fn lt(&self, other: &UseState<T>) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
§

fn partial_cmp(&self, other: &UseState<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
§

impl<T> Sub<T> for &UseState<T>where T: Sub + Copy,

§

type Output = <T as Sub>::Output

The resulting type after applying the - operator.
§

fn sub(self, other: T) -> <&UseState<T> as Sub<T>>::Output

Performs the - operation. Read more
§

impl<T> SubAssign<T> for &UseState<T>where T: Sub<Output = T> + Copy,

§

fn sub_assign(&mut self, rhs: T)

Performs the -= operation. Read more
§

impl<T> SubAssign<T> for UseState<T>where T: Sub<Output = T> + Copy,

§

fn sub_assign(&mut self, rhs: T)

Performs the -= operation. Read more

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for UseState<T>

§

impl<T> !Send for UseState<T>

§

impl<T> !Sync for UseState<T>

§

impl<T> Unpin for UseState<T>

§

impl<T> !UnwindSafe for UseState<T>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast for Twhere T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
§

impl<T> To for Twhere T: ?Sized,

§

fn to<T>(self) -> Twhere Self: Into<T>,

Converts to T by calling Into<T>::into.
§

fn try_to<T>(self) -> Result<T, Self::Error>where Self: TryInto<T>,

Tries to convert to T by calling TryInto<T>::try_into.
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
§

impl<T> ToSmolStr for Twhere T: Display + ?Sized,

§

fn to_smolstr(&self) -> SmolStr

source§

impl<T> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> CloneAny for Twhere T: Any + Clone,

§

impl<T> Dep for Twhere T: 'static + PartialEq + Clone,