I want to display the error
property for a createResource
.
In this example, why is error
set to undefined before being thrown.
It logs undefined
for the error before getting line error
import { render } from "solid-js/web";
import { For, createSignal, createResource, createEffect } from "solid-js";
const p_tau = async () => {
throw 'line error'
}
function Counter() {
let [s, setS] = createSignal()
let _r = createResource(s, _ => p_tau())
setInterval(() => {
setS(s() 'h')
}, 1000)
createEffect(() => {
console.log(_r[0].error)
})
return (<>
</>)
}
render(() => <Counter />, document.getElementById("app"));
CodePudding user response:
Because createResource
returns a resource and the initial value for a resource is always undefined
and remains undefined
until the promise returned from the fetcher function settles with a value:
import { createEffect, createResource, createSignal } from "solid-js";
import { render } from "solid-js/web";
const fetcher = async () => {
throw 'line error'
}
function Counter() {
let [s, setS] = createSignal(1);
let [data] = createResource(s, fetcher)
setInterval(() => {
setS(s => s 1);
}, 1000)
createEffect(() => {
console.log(data(), data.error);
})
return (<>
</>)
}
render(() => <Counter />, document.getElementById("app"));
Even if you pass a non-null sourceSignal
, it is same.
The promise resolves to a value in the next tick of the event loop and that is why even if you throw an immediate error, it does not immediately settles with an error. Solid's runtime executes synchronously. Consequently data.error
receives the error only after the next tick.