I have a chart component I want to reuse with different data.
Inside it I have a fetch function and a prop like so:
export let endpoint;
function getData(endpoint)
{
return fetch(endpoint)
.then((d) => d.json());
}
Later I use it this way:
$: data = getData(endpoint);
I pass the prop in the main page via:
<SingleBarChart endpoint={endpoint}/>
The error is:
throw new TypeError(‘Failed to parse URL from ‘ + input, { cause: err })
^
TypeError: Failed to parse URL from undefined
at new Request (D:\app\frontend\node_modules\undici\lib\fetch\request.js:77:15)
at Agent.fetch (D:\app\frontend\node_modules\undici\lib\fetch\index.js:116:21)
... 4 lines matching cause stack trace ...
at eval (/src/routes/+page.svelte:35:93)
at Object.$$render (/node_modules/svelte/internal/index.mjs:1772:22)
at Object.default (/.svelte-kit/generated/root.svelte:66:129)
at eval (/src/routes/+layout.svelte:16:32) {
[cause]: TypeError [ERR_INVALID_URL]: Invalid URL
at new NodeError (node:internal/errors:372:5)
at URL.onParseError (node:internal/url:563:9)
at new URL (node:internal/url:643:5)
at new Request (D:\app\frontend\node_modules\undici\lib\fetch\request.js:75:21)
at Agent.fetch (D:\app\frontend\node_modules\undici\lib\fetch\index.js:116:21)
at fetch (D:\app\frontend\node_modules\undici\index.js:95:22)
at getData (/src/lib/components/singleBarChart.svelte:13:9)
at eval (/src/lib/components/singleBarChart.svelte:47:9)
at Object.$$render (/node_modules/svelte/internal/index.mjs:1772:22)
at eval (/src/routes/+page.svelte:35:93) {
input: 'undefined',
code: 'ERR_INVALID_URL'
}
}
But, inside single barchart if I change
function getData()
{
return fetch("http://127.0.0.1:8000/md_events_team/shot").then((d) => d.json());
}
It works completely well.
I do not understand why, is it that $: getData(endpoint) here calls when endpoint is undefined?
It seems like that could be it, because if I give it a dummy URL it works and I can overwrite it too.
thanks a lot!
>Solution :
I will call whenever endpoint changes, including the very first time. So if initially endpoint is undefined it will try to call the function with endpoint. You can simply check the value before executing the function:
$: endpoint && (data = getData(endpoint));