0
0
Svelteframework~10 mins

Page load functions (+page.js) in Svelte - Interactive Code Practice

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

Complete the code to export a load function in +page.js that returns a simple message.

Svelte
export const load = async () => {
  return { message: [1] };
};
Drag options to blanks, or click blank then click option'
A"Hello from load"
BHello from load
C'Hello from load'
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the string
Returning a bare word without quotes
Not returning an object
2fill in blank
medium

Complete the code to import the 'fetch' function and use it inside the load function to get JSON data.

Svelte
export const load = async ({ [1] }) => {
  const res = await fetch('/api/data');
  const data = await res.json();
  return { data };
};
Drag options to blanks, or click blank then click option'
Aparams
Bfetch
Curl
Dsession
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'params' instead of 'fetch' when calling fetch
Not destructuring fetch from the argument
Trying to call fetch without destructuring
3fill in blank
hard

Fix the error in the load function by completing the code to return a 404 status when data is not found.

Svelte
export const load = async ({ fetch }) => {
  const res = await fetch('/api/item');
  if (!res.ok) {
    return { status: [1] };
  }
  const item = await res.json();
  return { item };
};
Drag options to blanks, or click blank then click option'
A404
B500
C200
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 200 even when data is missing
Using 0 or other invalid status codes
Using 500 which means server error
4fill in blank
hard

Fill both blanks to destructure 'params' and 'fetch' from the load function argument and fetch data using a dynamic id.

Svelte
export const load = async ({ [1], [2] }) => {
  const res = await fetch(`/api/item/${params.id}`);
  const item = await res.json();
  return { item };
};
Drag options to blanks, or click blank then click option'
Aparams
Burl
Cfetch
Dsession
Attempts:
3 left
💡 Hint
Common Mistakes
Not destructuring both params and fetch
Using wrong property names like url or session
Trying to access params without destructuring
5fill in blank
hard

Fill all three blanks to return a redirect status and location from the load function.

Svelte
export const load = async () => {
  return {
    status: [1],
    redirect: [2],
    message: [3]
  };
};
Drag options to blanks, or click blank then click option'
A302
B"/login"
C"Please login first"
D404
Attempts:
3 left
💡 Hint
Common Mistakes
Using 404 status for redirect
Not quoting string values for redirect and message
Returning redirect without status