create Previous Memo (Solid JS)
Get an accessor for the previous value of the provided signal. Returns
undefined
when the provided signal hasn't changed yet.
typescriptjavascript
export const createPreviousMemo = <T>(
get: Accessor<T>
): Accessor<T | undefined> => {
let currValue: T | undefined = undefined
const [prev, setPrev] = createSignal<T | undefined>()
createEffect(() => {
const nextValue = currValue
setPrev(() => nextValue)
currValue = get()
})
return prev
}
export const createPreviousMemo = get => {
let currValue = undefined
const [prev, setPrev] = createSignal()
createEffect(() => {
const nextValue = currValue
setPrev(() => nextValue)
currValue = get()
})
return prev
}
Usage
typescriptjavascript
import { type VoidComponent, createSignal } from 'solid-js'
const Example = () => {
const [count, setCount] = createSignal(0)
// Note - we're passing in an accessor / getter function and not the value
const previousCount = createPreviousMemo(count)
return (
<>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
<p>Current count: {count()}</p>
<p>Previous count: {previousCount().toString()}</p>
</>
)
}
import { createSignal } from 'solid-js'
const Example = () => {
const [count, setCount] = createSignal(0)
// Note - we're passing in an accessor / getter function and not the value
const previousCount = createPreviousMemo(count)
return (
<>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
<p>Current count: {count()}</p>
<p>Previous count: {previousCount().toString()}</p>
</>
)
}