0
0
Svelteframework~10 mins

Why load functions fetch data server-side in Svelte - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to fetch data inside a load function in SvelteKit.

Svelte
export async function load() {
  const response = await fetch([1]);
  const data = await response.json();
  return { data };
}
Drag options to blanks, or click blank then click option'
A"/api/data"
Bwindow.location
Cdocument.body
DlocalStorage.getItem('data')
Attempts:
3 left
💡 Hint
Common Mistakes
Using browser-only objects like window or document inside load causes errors.
Trying to fetch from localStorage instead of a URL.
2fill in blank
medium

Complete the load function to return the fetched data correctly.

Svelte
export async function load() {
  const res = await fetch('/api/info');
  const info = await res.json();
  return [1];
}
Drag options to blanks, or click blank then click option'
A{ info }
B{ props: info }
C{ props: { info } }
D{ data: info }
Attempts:
3 left
💡 Hint
Common Mistakes
Wrapping in an unnecessary props object like Next.js getServerSideProps.
Returning the data directly (e.g. return info;) without an object.
3fill in blank
hard

Fix the error in the load function to fetch data server-side without using browser globals.

Svelte
export async function load() {
  const data = await [1].then(res => res.json());
  return { data };
}
Drag options to blanks, or click blank then click option'
Afetch('http://localhost/api/data')
Bfetch(document.location)
Cfetch('/api/data')
Dfetch(localStorage.getItem('url'))
Attempts:
3 left
💡 Hint
Common Mistakes
Using window or document inside load causes runtime errors.
Hardcoding full URLs can cause issues in different environments.
4fill in blank
hard

Fill both blanks to fetch JSON data and return it properly in a load function.

Svelte
export async function load() {
  const response = await fetch([1]);
  const jsonData = await response.[2]();
  return { jsonData };
}
Drag options to blanks, or click blank then click option'
A"/api/items"
Bjson
Ctext
D"/data.json"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text' instead of 'json' to parse JSON data.
Passing non-string values as the fetch URL.
5fill in blank
hard

Fill all three blanks to fetch data, check response status, and return props in a load function.

Svelte
export async function load() {
  const res = await fetch([1]);
  if (!res.[2]) {
    throw new Error('Failed to fetch');
  }
  const data = await res.[3]();
  return { data };
}
Drag options to blanks, or click blank then click option'
A"/api/users"
Bok
Cjson
Dstatus
Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'status' directly instead of 'ok' boolean.
Not parsing the response as JSON before returning.