Struct leptos::MaybeProp

source ·
pub struct MaybeProp<T>(/* private fields */)
where
    T: 'static;
Expand description

A wrapping type for an optional component prop, which can either be a signal or a non-reactive value, and which may or may not have a value. In other words, this is an Option<MaybeSignal<Option<T>>> that automatically flattens its getters.

This creates an extremely flexible type for component libraries, etc.

§Core Trait Implementations

  • .get() (or calling the signal as a function) clones the current value of the signal. If you call it within an effect, it will cause that effect to subscribe to the signal, and to re-run whenever the value of the signal changes.
    • .get_untracked() clones the value of the signal without reactively tracking it.
  • .with() allows you to reactively access the signal’s value without cloning by applying a callback function.
    • .with_untracked() allows you to access the signal’s value without reactively tracking it.
  • .to_stream() converts the signal to an async stream of values.

§Examples

let (count, set_count) = create_signal(Some(2));
let double = |n| n * 2;
let double_count = MaybeProp::derive(move || count.get().map(double));
let memoized_double_count = create_memo(move |_| count.get().map(double));
let static_value = 5;

// this function takes either a reactive or non-reactive value
fn above_3(arg: &MaybeProp<i32>) -> bool {
    // ✅ calling the signal clones and returns the value
    //    it is a shorthand for arg.get()q
    arg.get().map(|arg| arg > 3).unwrap_or(false)
}

assert_eq!(above_3(&None::<i32>.into()), false);
assert_eq!(above_3(&static_value.into()), true);
assert_eq!(above_3(&count.into()), false);
assert_eq!(above_3(&double_count), true);
assert_eq!(above_3(&memoized_double_count.into()), true);

Implementations§

source§

impl<T> MaybeProp<T>

§Examples

let (name, set_name) = create_signal("Alice".to_string());
let (maybe_name, set_maybe_name) = create_signal(None);
let name_upper =
    MaybeProp::derive(move || Some(name.with(|n| n.to_uppercase())));
let memoized_lower = create_memo(move |_| name.with(|n| n.to_lowercase()));
let static_value: MaybeProp<String> = "Bob".to_string().into();

// this function takes any kind of wrapped signal
fn current_len_inefficient(arg: &MaybeProp<String>) -> usize {
    // ❌ unnecessarily clones the string
    arg.get().map(|n| n.len()).unwrap_or(0)
}

fn current_len(arg: &MaybeProp<String>) -> usize {
    // ✅ gets the length without cloning the `String`
    arg.with(|value| value.len()).unwrap_or(0)
}

assert_eq!(current_len(&None::<String>.into()), 0);
assert_eq!(current_len(&maybe_name.into()), 0);
assert_eq!(current_len(&name_upper), 5);
assert_eq!(current_len(&memoized_lower.into()), 5);
assert_eq!(current_len(&static_value), 3);

// Normal signals/memos return T
assert_eq!(name.get(), "Alice".to_string());
assert_eq!(memoized_lower.get(), "alice".to_string());

// MaybeProp::get() returns Option<T>
assert_eq!(name_upper.get(), Some("ALICE".to_string()));
assert_eq!(static_value.get(), Some("Bob".to_string()));
source

pub fn with<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O>

Applies a function to the current value, returning the result.

source

pub fn try_with<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O>

Applies a function to the current value, returning the result. Returns None if the value has already been disposed.

source

pub fn with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O>

Applies a function to the current value, returning the result, without causing the current reactive scope to track changes.

source

pub fn try_with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O>

Applies a function to the current value, returning the result, without causing the current reactive scope to track changes. Returns None if the value has already been disposed.

source§

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

source

pub fn derive(derived_signal: impl Fn() -> Option<T> + 'static) -> MaybeProp<T>

Wraps a derived signal, i.e., any computation that accesses one or more reactive signals.

let (count, set_count) = create_signal(2);
let double_count = MaybeProp::derive(move || Some(count.get() * 2));

// this function takes any kind of wrapped signal
fn above_3(arg: &MaybeProp<i32>) -> bool {
    arg.get().unwrap_or(0) > 3
}

assert_eq!(above_3(&count.into()), false);
assert_eq!(above_3(&double_count.into()), true);
assert_eq!(above_3(&2.into()), false);

Trait Implementations§

source§

impl<T> Clone for MaybeProp<T>
where T: Clone + 'static,

source§

fn clone(&self) -> MaybeProp<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
source§

impl<T> Debug for MaybeProp<T>
where T: Debug + 'static,

source§

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

Formats the value using the given formatter. Read more
source§

impl<T> Default for MaybeProp<T>

source§

fn default() -> MaybeProp<T>

Returns the “default value” for a type. Read more
source§

impl From<&str> for MaybeProp<String>

source§

fn from(value: &str) -> MaybeProp<String>

Converts to this type from the input type.
source§

impl From<&'static str> for MaybeProp<TextProp>

source§

fn from(s: &'static str) -> MaybeProp<TextProp>

Converts to this type from the input type.
source§

impl From<Box<str>> for MaybeProp<TextProp>

source§

fn from(s: Box<str>) -> MaybeProp<TextProp>

Converts to this type from the input type.
source§

impl From<Cow<'static, str>> for MaybeProp<TextProp>

source§

fn from(s: Cow<'static, str>) -> MaybeProp<TextProp>

Converts to this type from the input type.
source§

impl<T> From<MaybeSignal<Option<T>>> for MaybeProp<T>

source§

fn from(value: MaybeSignal<Option<T>>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl<T> From<Memo<Option<T>>> for MaybeProp<T>

source§

fn from(value: Memo<Option<T>>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl<T> From<Memo<T>> for MaybeProp<T>
where T: Clone,

source§

fn from(value: Memo<T>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl<T> From<Option<MaybeSignal<Option<T>>>> for MaybeProp<T>

source§

fn from(value: Option<MaybeSignal<Option<T>>>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl<T> From<Option<T>> for MaybeProp<T>

source§

fn from(value: Option<T>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl From<Rc<str>> for MaybeProp<TextProp>

source§

fn from(s: Rc<str>) -> MaybeProp<TextProp>

Converts to this type from the input type.
source§

impl<T> From<ReadSignal<Option<T>>> for MaybeProp<T>

source§

fn from(value: ReadSignal<Option<T>>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl<T> From<ReadSignal<T>> for MaybeProp<T>
where T: Clone,

source§

fn from(value: ReadSignal<T>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl<T> From<RwSignal<Option<T>>> for MaybeProp<T>

source§

fn from(value: RwSignal<Option<T>>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl<T> From<RwSignal<T>> for MaybeProp<T>
where T: Clone,

source§

fn from(value: RwSignal<T>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl<T> From<Signal<Option<T>>> for MaybeProp<T>

source§

fn from(value: Signal<Option<T>>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl<T> From<Signal<T>> for MaybeProp<T>
where T: Clone,

source§

fn from(value: Signal<T>) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl From<String> for MaybeProp<TextProp>

source§

fn from(s: String) -> MaybeProp<TextProp>

Converts to this type from the input type.
source§

impl<T> From<T> for MaybeProp<T>

source§

fn from(value: T) -> MaybeProp<T>

Converts to this type from the input type.
source§

impl<T> IntoAttribute for MaybeProp<T>
where T: IntoAttribute + Clone,

source§

fn into_attribute(self) -> Attribute

Converts the object into an Attribute.
source§

fn into_attribute_boxed(self: Box<MaybeProp<T>>) -> Attribute

Helper function for dealing with Box<dyn IntoAttribute>.
source§

impl IntoClass for MaybeProp<bool>

source§

fn into_class(self) -> Class

Converts the object into a Class.
source§

fn into_class_boxed(self: Box<MaybeProp<bool>>) -> Class

Helper function for dealing with Box<dyn IntoClass>.
source§

impl<T> IntoProperty for MaybeProp<T>
where T: Clone, Option<T>: Into<JsValue>,

source§

fn into_property(self) -> Property

Converts the object into a Property.
source§

fn into_property_boxed(self: Box<MaybeProp<T>>) -> Property

Helper function for dealing with Box<dyn IntoProperty>.
source§

impl<T> IntoStyle for MaybeProp<T>
where T: Clone, Option<T>: IntoStyle,

source§

fn into_style(self) -> Style

Converts the object into a Style.
source§

fn into_style_boxed(self: Box<MaybeProp<T>>) -> Style

Helper function for dealing with Box<dyn IntoStyle>.
source§

impl<T> IntoView for MaybeProp<T>
where T: IntoView + Clone,

source§

fn into_view(self) -> View

Converts the value into View.
source§

impl<T> PartialEq for MaybeProp<T>
where T: PartialEq + 'static,

source§

fn eq(&self, other: &MaybeProp<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.
source§

impl<T> Serialize for MaybeProp<T>
where T: Serialize,

source§

fn serialize<S>( &self, serializer: S ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl<T> SignalGet for MaybeProp<T>
where T: Clone,

§Examples

let (count, set_count) = create_signal(Some(2));
let double = |n| n * 2;
let double_count = MaybeProp::derive(move || count.get().map(double));
let memoized_double_count = create_memo(move |_| count.get().map(double));
let static_value = 5;

// this function takes either a reactive or non-reactive value
fn above_3(arg: &MaybeProp<i32>) -> bool {
    // ✅ calling the signal clones and returns the value
    //    it is a shorthand for arg.get()q
    arg.get().map(|arg| arg > 3).unwrap_or(false)
}

assert_eq!(above_3(&None::<i32>.into()), false);
assert_eq!(above_3(&static_value.into()), true);
assert_eq!(above_3(&count.into()), false);
assert_eq!(above_3(&double_count), true);
assert_eq!(above_3(&memoized_double_count.into()), true);
§

type Value = Option<T>

The value held by the signal.
source§

fn get(&self) -> Option<T>

Clones and returns the current value of the signal, and subscribes the running effect to this signal. Read more
source§

fn try_get(&self) -> Option<Option<T>>

Clones and returns the signal value, returning Some if the signal is still alive, and None otherwise.
source§

impl<T> SignalGetUntracked for MaybeProp<T>
where T: Clone,

§

type Value = Option<T>

The value held by the signal.
source§

fn get_untracked(&self) -> Option<T>

Gets the signal’s value without creating a dependency on the current scope. Read more
source§

fn try_get_untracked(&self) -> Option<Option<T>>

Gets the signal’s value without creating a dependency on the current scope. Returns [Some(T)] if the signal is still valid, None otherwise.
source§

impl<T> SignalStream<Option<T>> for MaybeProp<T>
where T: Clone,

source§

fn to_stream(&self) -> Pin<Box<dyn Stream<Item = Option<T>>>>

Generates a Stream that emits the new value of the signal whenever it changes. Read more
source§

impl<T> Copy for MaybeProp<T>
where T: Copy,

source§

impl<T> Eq for MaybeProp<T>
where T: Eq + 'static,

source§

impl<T> StructuralPartialEq for MaybeProp<T>
where T: 'static,

Auto Trait Implementations§

§

impl<T> Freeze for MaybeProp<T>
where T: Freeze,

§

impl<T> !RefUnwindSafe for MaybeProp<T>

§

impl<T> !Send for MaybeProp<T>

§

impl<T> !Sync for MaybeProp<T>

§

impl<T> Unpin for MaybeProp<T>
where T: Unpin,

§

impl<T> !UnwindSafe for MaybeProp<T>

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<T> From<!> for T

source§

fn from(t: !) -> T

Converts to this type from the input type.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<CustErr, T, Request> FromReq<Streaming, Request, CustErr> for T
where Request: Req<CustErr> + Send + 'static, T: From<ByteStream> + 'static,

source§

async fn from_req(req: Request) -> Result<T, ServerFnError<CustErr>>

Attempts to deserialize the arguments from a request.
source§

impl<CustErr, T, Request> FromReq<StreamingText, Request, CustErr> for T
where Request: Req<CustErr> + Send + 'static, T: From<TextStream> + 'static,

source§

async fn from_req(req: Request) -> Result<T, ServerFnError<CustErr>>

Attempts to deserialize the arguments from a request.
source§

impl<T> Instrument for T

source§

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

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

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 T
where 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.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> ToOwned for T
where 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
source§

impl<T, U> TryFrom<U> for T
where 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 T
where 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.
source§

impl<T> WithSubscriber for T

source§

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
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<El> ElementDescriptorBounds for El
where El: Debug,