use_on_unmount.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /// Creates 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 app(cx: Scope) -> Element {
  7. /// let state = use_state(cx, || true);
  8. /// render! {
  9. /// for _ in 0..100 {
  10. /// h1 {
  11. /// "spacer"
  12. /// }
  13. /// }
  14. /// if **state {
  15. /// render! {
  16. /// child_component {}
  17. /// }
  18. /// }
  19. /// button {
  20. /// onclick: move |_| {
  21. /// state.set(!*state.get());
  22. /// },
  23. /// "Unmount element"
  24. /// }
  25. /// }
  26. /// }
  27. /// fn child_component(cx: Scope) -> Element {
  28. /// let original_scroll_position = use_state(cx, || 0.0);
  29. /// use_effect(cx, (), move |_| {
  30. /// to_owned![original_scroll_position];
  31. /// async move {
  32. /// let window = web_sys::window().unwrap();
  33. /// let document = window.document().unwrap();
  34. /// let element = document.get_element_by_id("my_element").unwrap();
  35. /// element.scroll_into_view();
  36. /// original_scroll_position.set(window.scroll_y().unwrap());
  37. /// }
  38. /// });
  39. /// use_on_unmount(cx, {
  40. /// to_owned![original_scroll_position];
  41. /// /// restore scroll to the top of the page
  42. /// move || {
  43. /// let window = web_sys::window().unwrap();
  44. /// window.scroll_with_x_and_y(*original_scroll_position.current(), 0.0);
  45. /// }
  46. /// });
  47. /// render!{
  48. /// div {
  49. /// id: "my_element",
  50. /// "hello"
  51. /// }
  52. /// }
  53. /// }
  54. /// ```
  55. pub fn use_on_unmount<D: FnOnce() + 'static>(cx: &dioxus_core::ScopeState, destroy: D) {
  56. cx.use_hook(|| LifeCycle {
  57. ondestroy: Some(destroy),
  58. });
  59. }
  60. struct LifeCycle<D: FnOnce()> {
  61. ondestroy: Option<D>,
  62. }
  63. impl<D: FnOnce()> Drop for LifeCycle<D> {
  64. fn drop(&mut self) {
  65. let f = self.ondestroy.take().unwrap();
  66. f();
  67. }
  68. }