0
0
Svelteframework~30 mins

Response helpers (json, error) in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Response helpers (json, error) in Svelte
📖 Scenario: You are building a simple Svelte app that fetches data from an API. You want to create helper functions to handle JSON responses and errors cleanly.
🎯 Goal: Build two helper functions: json to format JSON responses and error to create error responses. Use these helpers in a Svelte component to show success or error messages.
📋 What You'll Learn
Create a json helper function that returns an object with status and body properties.
Create an error helper function that returns an object with status and body containing an error message.
Use these helpers in a Svelte component to display a success message or an error message based on a simulated API call.
Follow Svelte syntax and patterns for reactive variables and event handling.
💡 Why This Matters
🌍 Real World
Creating helper functions to standardize API responses helps keep frontend code clean and consistent when handling data and errors.
💼 Career
Understanding how to handle JSON and error responses is essential for frontend developers working with APIs and building interactive web apps.
Progress0 / 4 steps
1
Create the json helper function
Create a function called json that takes two parameters: data and status. It should return an object with status set to the passed status and body set to the passed data.
Svelte
Hint

Think of json as a way to package data with a status code.

2
Create the error helper function
Create a function called error that takes two parameters: status and message. It should return an object with status set to the passed status and body set to an object with a message property containing the passed message.
Svelte
Hint

The error function packages an error message with a status code.

3
Set up Svelte component state variables
In a Svelte component, create two reactive variables: response initialized to null and errorMessage initialized to an empty string ''.
Svelte
Hint

Use let to declare reactive variables in Svelte.

4
Add a function to simulate API call and display response
Add a function called fetchData inside the <script> tag. It should simulate a successful API call by setting response to the result of json({ message: 'Success!' }, 200) and clear errorMessage. Also add a button in the markup that calls fetchData on click. Below the button, display response.body.message if response exists, or errorMessage if it is not empty.
Svelte
Hint

Use Svelte's on:click event to call fetchData.