yew icon indicating copy to clipboard operation
yew copied to clipboard

Define prop execution order

Open siku2 opened this issue 5 years ago • 0 comments

The execution order of prop value expressions is in alphabetic order based on the prop key. Let's look at an example:

/// Gen is used here to simulate a stateful expression
#[derive(Default)]
struct Gen {
    state: usize,
}
impl Gen {
    fn next(&mut self) -> usize {
        self.state += 1;
        self.state
    }
}

fn main() {
    // the order in which `g.next()` is called matters!
    let mut g = Gen::default();
    let props = yew::props!(Props {
        my_first: g.next(),
        second: g.next(),
        last: g.next(),
    });

    // different order!
    assert_eq!(props.last, 1);
    assert_eq!(props.my_first, 2);
    assert_eq!(props.second, 3);
}

Normally Clippy warns about execution order in struct expressions, but we don't have the tools to do this, especially not in the html! macro. The easiest way to avoid confusion here is to define the execution order as the one defined by the user.

To achieve this for components we just need to pre-evaluate the prop values before using them in the builder. Elements are a bit more painful because of the different special props but the same idea can still be used.

This isn't a high priority issue right now but it could save a few headaches down the line.

siku2 avatar Oct 28 '20 17:10 siku2