context_api.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. use dioxus::dioxus_core::{ElementId, Mutation::*};
  2. use dioxus::prelude::*;
  3. #[test]
  4. fn state_shares() {
  5. fn app() -> Element {
  6. provide_context(generation() as i32);
  7. rsx!(child_1 {})
  8. }
  9. fn child_1() -> Element {
  10. rsx!(child_2 {})
  11. }
  12. fn child_2() -> Element {
  13. let value = consume_context::<i32>();
  14. rsx!("Value is {value}")
  15. }
  16. let mut dom = VirtualDom::new(app);
  17. assert_eq!(
  18. dom.rebuild_to_vec().santize().edits,
  19. [
  20. CreateTextNode { value: "Value is 0".to_string(), id: ElementId(1,) },
  21. AppendChildren { m: 1, id: ElementId(0) },
  22. ]
  23. );
  24. dom.mark_dirty(ScopeId::ROOT);
  25. _ = dom.render_immediate_to_vec();
  26. dom.in_runtime(|| {
  27. assert_eq!(ScopeId::ROOT.consume_context::<i32>().unwrap(), 1);
  28. });
  29. dom.mark_dirty(ScopeId::ROOT);
  30. _ = dom.render_immediate_to_vec();
  31. dom.in_runtime(|| {
  32. assert_eq!(ScopeId::ROOT.consume_context::<i32>().unwrap(), 2);
  33. });
  34. dom.mark_dirty(ScopeId(2));
  35. assert_eq!(
  36. dom.render_immediate_to_vec().santize().edits,
  37. [SetText { value: "Value is 2".to_string(), id: ElementId(1,) },]
  38. );
  39. dom.mark_dirty(ScopeId::ROOT);
  40. dom.mark_dirty(ScopeId(2));
  41. let edits = dom.render_immediate_to_vec();
  42. assert_eq!(
  43. edits.santize().edits,
  44. [SetText { value: "Value is 3".to_string(), id: ElementId(1,) },]
  45. );
  46. }