use_on_unmount.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /// Creats a callback that will be run before the component is removed. This can be used to clean up side effects from the component (created with use_effect)
  2. ///
  3. /// Example:
  4. /// ```rust
  5. /// use dioxus::prelude::*;
  6. /// fn main() {
  7. /// dioxus_web::launch(app)
  8. /// }
  9. /// fn app(cx: Scope) -> Element {
  10. /// let state = use_state(cx, || true);
  11. /// render! {
  12. /// for _ in 0..100 {
  13. /// h1 {
  14. /// "spacer"
  15. /// }
  16. /// }
  17. /// if **state {
  18. /// render! {
  19. /// child_component {}
  20. /// }
  21. /// }
  22. /// button {
  23. /// onclick: move |_| {
  24. /// state.set(!*state.get());
  25. /// },
  26. /// "Unmount element"
  27. /// }
  28. /// }
  29. /// }
  30. /// fn child_component(cx: Scope) -> Element {
  31. /// let original_scroll_position = use_state(cx, || 0.0);
  32. /// use_effect(cx, (), move |_| {
  33. /// to_owned![original_scroll_position];
  34. /// async move {
  35. /// let window = web_sys::window().unwrap();
  36. /// let document = window.document().unwrap();
  37. /// let element = document.get_element_by_id("my_element").unwrap();
  38. /// element.scroll_into_view();
  39. /// original_scroll_position.set(window.scroll_y().unwrap());
  40. /// }
  41. /// });
  42. /// use_on_unmount(cx, {
  43. /// to_owned![original_scroll_position];
  44. /// /// restore scroll to the top of the page
  45. /// move || {
  46. /// let window = web_sys::window().unwrap();
  47. /// window.scroll_with_x_and_y(*original_scroll_position.current(), 0.0);
  48. /// }
  49. /// });
  50. /// render!{
  51. /// div {
  52. /// id: "my_element",
  53. /// "hello"
  54. /// }
  55. /// }
  56. /// }
  57. /// ```
  58. pub fn use_on_unmount<C: FnOnce() + 'static, D: FnOnce() + 'static>(cx: &ScopeState, destroy: D) {
  59. cx.use_hook(|| LifeCycle {
  60. ondestroy: Some(destroy),
  61. });
  62. }
  63. struct LifeCycle<D: FnOnce()> {
  64. ondestroy: Option<D>,
  65. }
  66. impl<D: FnOnce()> Drop for LifeCycle<D> {
  67. fn drop(&mut self) {
  68. let f = self.ondestroy.take().unwrap();
  69. f();
  70. }
  71. }