Reputation: 107
Is it possible to consume external REST api in components? With the new breaking changes, I couldn't find an updated answer.
Appreciate any help.
Upvotes: 2
Views: 3771
Reputation: 350
Good example from docs: https://kit.svelte.dev/docs/load#making-fetch-requests
/** @type {import('./$types').PageLoad} */
export async function load({ fetch, params }) {
const res = await fetch(`/api/items/${params.id}`);
const item = await res.json();
return { item };
}
Upvotes: 0
Reputation: 413
Sure!
You can do a native fetch
for any CRUD
operations inside components.
Something similar like this:
let data;
const getData = async () => {
const response = await fetch('https://your.endpoint/api/foo');
if (response.headers.get('content-type')?.includes('application/json')) {
const json = await response.json();
return { response, json };
} else {
return { response };
}
};
Then you can initialize whenever you want. E.g:
onMount(async ()=> {
await getData();
})
Upvotes: 1