Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To incorporate an external backend into SvelteKit, you can use an HTTP client library like Axios or Fetch API to make requests to the backend server. You can create a "service" module to abstract away the details of making requests and parsing responses, and then import that service into your Svelte components.

Here's an example of what your service module might look like using Axios:

// api.js
import axios from 'axios';

const API_URL = 'https://example.com/api';

export async function getTodos() {
  const response = await axios.get(`${API_URL}/todos`);
  return response.data;
}

export async function createTodo(todo) {
  const response = await axios.post(`${API_URL}/todos`, todo);
  return response.data;
}

// etc.

Then, you can import these functions into your Svelte components and use them like this:

<script>
import { getTodos } from '../api.js';

let todos = [];

async function loadTodos() {
  todos = await getTodos();
}
</script>

<button on:click={loadTodos}>Load Todos</button>

<ul>
  {#each todos as todo}
    <li>{todo.title}</li>
  {/each}
</ul>

Note that this example assumes that your backend API returns data in JSON format. If your API returns data in a different format, you may need to modify the code accordingly.