Created
April 4, 2023 09:09
-
-
Save myobie/902ec774627c4904b67d3f2b11c61f52 to your computer and use it in GitHub Desktop.
Sometimes I want to know the previous value for an effect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { effect } from '@preact/signals-core' | |
export function effectWithPreviousValue<T>( | |
initialValue: T, | |
compute: (prev: T) => T | |
): () => void { | |
let prev = initialValue | |
return effect(() => { | |
prev = compute(prev) | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"imports": { | |
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3", | |
"std/": "https://deno.land/std@0.182.0/" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { effectWithPreviousValue } from './effect-with-previous-value.ts' | |
import { signal } from '@preact/signals-core' | |
import { assertEquals } from 'std/testing/asserts.ts' | |
Deno.test('receives the previous returned value for each effect run', () => { | |
let counterIncreasedByMoreThanTwo = false | |
let effectRunCount = 0 | |
const counter = signal(0) | |
const dispose = effectWithPreviousValue<number>(0, prevNum => { | |
effectRunCount += 1 | |
if (counter.value > prevNum + 2) { | |
counterIncreasedByMoreThanTwo = true | |
} | |
return counter.value | |
}) | |
try { | |
assertEquals(effectRunCount, 1) | |
assertEquals(counterIncreasedByMoreThanTwo, false) | |
counter.value = 1 | |
assertEquals(effectRunCount, 2) | |
assertEquals(counterIncreasedByMoreThanTwo, false) | |
counter.value = 5 | |
assertEquals(effectRunCount, 3) | |
assertEquals(counterIncreasedByMoreThanTwo, true) | |
} finally { | |
dispose() | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment