solidjs style computeds & async computeds
Author: btakitaCreated Apr 28, 2023Updated Sep 21, 2026
Solidjs signals use inline dependencies, removing the redundancy of declaring the dependency atoms when the computed is defined. I think we can lazily add dependencies when the computed function is executed.
Perhaps it could look something like:
const base = atom(0)
const dependency = computed(()=>base() + 1)
console.info({ dependency: dependency() })
dependency.unbind()I think it would work even if a dependency is not reached in a particular execution...
const base0 = atom(0)
const base1 = atom('foobar')
const dependency = computed(()=>{
if (base0() >= 2) return base1()
return 'baz'
})
console.info(dependency()) // 'baz'
// dependency does not yet listen to base1
base0.set(1)
console.info(dependency()) // 'baz'
// dependency now listens to base1
base0.set(2)
console.info(dependency()) // 'foobar'
dependency.unbind()It could also work for async as well. Given that the get function argument is necessary to push the caller to the caller stack to track the which computed will be subscribing to the dependency. Solidjs memos are synchronous, so there is no equivalent.
const base = atom(0)
const retry_id = atom(0)
const dependency = computed(async (get, set)=>{
set({ loading: true })
const response = await fetch(`https://my-api/api?id=${get(base)}`)
const payload = await response.json()
set({
payload,
retry_id: get(retry_id)
})
})
console.info({ dependency: dependency() }) // { loading: true }
// wait for first response
console.info({ dependency: dependency() }) // { payload: { ... }, retry_id: 0 }
retry_id.set(retry_id.get() + 1)
// wait for second response
console.info({ dependency: dependency() }) // { payload: { ... }, retry_id: 1 }
dependency.unbind()or get could be used as a sort of self argument
const base = atom(0)
const retry_id = atom(0)
const dependency = computed(async (self, set)=>{
set({ loading: true })
const response = await fetch(`https://my-api/api?id=${base.get(self)}`)
const payload = await response.json()
set({
payload,
retry_id: retry_id.get(self)
})
})This could also be a separate library which imports nanostores.
Source: nanostores/nanostores