pull/16278/head
Rich Harris 3 months ago
parent 85268bc147
commit 0ad95885f3

@ -26,7 +26,7 @@ import {
} from './constants.js';
import { flush_tasks } from './dom/task.js';
import { internal_set, old_values } from './reactivity/sources.js';
import { destroy_derived_effects, update_derived } from './reactivity/deriveds.js';
import { destroy_derived_effects, execute_derived, update_derived } from './reactivity/deriveds.js';
import * as e from './errors.js';
import { tracing_mode_flag } from '../flags/index.js';
@ -764,7 +764,7 @@ export function get(signal) {
}
}
if (is_derived) {
if (is_derived && !is_destroying_effect) {
derived = /** @type {Derived} */ (signal);
if (check_dirtiness(derived)) {
@ -805,8 +805,19 @@ export function get(signal) {
}
}
if (is_destroying_effect && old_values.has(signal)) {
return old_values.get(signal);
if (is_destroying_effect) {
if (old_values.has(signal)) {
return old_values.get(signal);
}
if (is_derived) {
derived = /** @type {Derived} */ (signal);
var value = execute_derived(derived);
old_values.set(derived, value);
return value;
}
}
return signal.v;

@ -3,37 +3,20 @@ import { test } from '../../test';
export default test({
async test({ assert, logs, target }) {
/** @type {HTMLButtonElement | null} */
const increment_btn = target.querySelector('#increment');
/** @type {HTMLButtonElement | null} */
const overwrite_btn = target.querySelector('#overwrite');
const [increment] = target.querySelectorAll('button');
// Initial state: count=1, derived_value=1
flushSync(() => increment.click());
flushSync(() => increment.click());
flushSync(() => increment.click());
// Click to increment count: count=2, derived_value=4
flushSync(() => {
increment_btn?.click();
});
// Click to increment count: count=3, derived_value=9
flushSync(() => {
increment_btn?.click();
});
// Click to overwrite derived_value: count=3, derived_value=7
flushSync(() => {
overwrite_btn?.click();
});
// Should log old value during cleanup (4) and new value during setup (9)
assert.deepEqual(logs, [
'$effect: 1',
'$effect teardown: 1',
'$effect: 4',
'$effect teardown: 4',
'$effect: 9',
'$effect teardown: 9',
'$effect: 7'
'count: 1',
'squared: 1',
'count: 2',
'squared: 4',
'count: 3',
'squared: 9',
'count: 4'
]);
}
});

@ -1,17 +1,20 @@
<script>
let count = $state(1);
let derived_value = $derived(count * count);
let squared = $derived(count * count);
$effect(() => {
console.log(`$effect: ${derived_value}`);
console.log(`count: ${count}`);
return () => {
console.log(`$effect teardown: ${derived_value}`);
console.log(`squared: ${squared}`);
};
});
</script>
<button id="increment" onclick={() => count++}>Increment s</button>
<button id="overwrite" onclick={() => (derived_value = 7)}>Overwrite derived_value</button>
<button onclick={() => count++}>increment</button>
<p>count: {count}</p>
<p>derived_value: {derived_value}</p>
{#if count % 2 === 0}
<p id="squared">squared: {squared}</p>
{/if}

Loading…
Cancel
Save