2022-08-11 02:34:20 +00:00
|
|
|
use leptos_reactive::create_scope;
|
2022-08-08 18:09:16 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn effect_runs() {
|
|
|
|
use std::cell::RefCell;
|
|
|
|
use std::rc::Rc;
|
|
|
|
|
2022-08-11 02:34:20 +00:00
|
|
|
create_scope(|cx| {
|
2022-08-08 18:09:16 +00:00
|
|
|
let (a, set_a) = cx.create_signal(-1);
|
|
|
|
|
|
|
|
// simulate an arbitrary side effect
|
|
|
|
let b = Rc::new(RefCell::new(String::new()));
|
|
|
|
|
|
|
|
cx.create_effect({
|
|
|
|
let b = b.clone();
|
2022-08-11 02:34:20 +00:00
|
|
|
move |_| {
|
2022-08-08 18:09:16 +00:00
|
|
|
let formatted = format!("Value is {}", a());
|
|
|
|
*b.borrow_mut() = formatted;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
assert_eq!(b.borrow().as_str(), "Value is -1");
|
|
|
|
|
|
|
|
set_a(|a| *a = 1);
|
|
|
|
|
|
|
|
assert_eq!(b.borrow().as_str(), "Value is 1");
|
2022-08-11 02:34:20 +00:00
|
|
|
})
|
|
|
|
.dispose()
|
2022-08-08 18:09:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn effect_tracks_memo() {
|
|
|
|
use std::cell::RefCell;
|
|
|
|
use std::rc::Rc;
|
|
|
|
|
2022-08-11 02:34:20 +00:00
|
|
|
create_scope(|cx| {
|
2022-08-08 18:09:16 +00:00
|
|
|
let (a, set_a) = cx.create_signal(-1);
|
2022-08-11 02:34:20 +00:00
|
|
|
let b = cx.create_memo(move |_| format!("Value is {}", a()));
|
2022-08-08 18:09:16 +00:00
|
|
|
|
|
|
|
// simulate an arbitrary side effect
|
|
|
|
let c = Rc::new(RefCell::new(String::new()));
|
|
|
|
|
|
|
|
cx.create_effect({
|
|
|
|
let c = c.clone();
|
2022-08-11 02:34:20 +00:00
|
|
|
move |_| {
|
2022-08-08 18:09:16 +00:00
|
|
|
*c.borrow_mut() = b();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
assert_eq!(b().as_str(), "Value is -1");
|
|
|
|
assert_eq!(c.borrow().as_str(), "Value is -1");
|
|
|
|
|
|
|
|
set_a(|a| *a = 1);
|
|
|
|
|
|
|
|
assert_eq!(b().as_str(), "Value is 1");
|
|
|
|
assert_eq!(c.borrow().as_str(), "Value is 1");
|
2022-08-11 02:34:20 +00:00
|
|
|
})
|
|
|
|
.dispose()
|
2022-08-08 18:09:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn untrack_mutes_effect() {
|
|
|
|
use std::cell::RefCell;
|
|
|
|
use std::rc::Rc;
|
|
|
|
|
2022-08-11 02:34:20 +00:00
|
|
|
create_scope(|cx| {
|
2022-08-08 18:09:16 +00:00
|
|
|
let (a, set_a) = cx.create_signal(-1);
|
|
|
|
|
|
|
|
// simulate an arbitrary side effect
|
|
|
|
let b = Rc::new(RefCell::new(String::new()));
|
|
|
|
|
|
|
|
cx.create_effect({
|
|
|
|
let b = b.clone();
|
2022-08-11 02:34:20 +00:00
|
|
|
move |_| {
|
2022-08-08 18:09:16 +00:00
|
|
|
let formatted = format!("Value is {}", cx.untrack(a));
|
|
|
|
*b.borrow_mut() = formatted;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
assert_eq!(a(), -1);
|
|
|
|
assert_eq!(b.borrow().as_str(), "Value is -1");
|
|
|
|
|
|
|
|
set_a(|a| *a = 1);
|
|
|
|
|
|
|
|
assert_eq!(a(), 1);
|
|
|
|
assert_eq!(b.borrow().as_str(), "Value is -1");
|
2022-08-11 02:34:20 +00:00
|
|
|
})
|
|
|
|
.dispose()
|
2022-08-08 18:09:16 +00:00
|
|
|
}
|