use_on_destroy.rs 2.6 KB

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