0
0
Svelteframework~5 mins

Invalidation and reloading in Svelte

Choose your learning style9 modes available
Introduction

Invalidation and reloading help keep your app's data fresh by updating it when something changes.

When you want to refresh data after a user action like submitting a form.
When external data changes and your app needs to show the latest info.
When navigating between pages that share data and you want to reload it.
When you want to avoid showing outdated information to users.
Syntax
Svelte
import { invalidate } from '$app/navigation';

// To reload data for a route
await invalidate('route-or-url');

invalidate is an async function that tells SvelteKit to reload data for a given route or URL.

You can call invalidate() without arguments to reload the current page's data.

Examples
This reloads the data for the current page, useful after a user updates something.
Svelte
import { invalidate } from '$app/navigation';

// Reload current page data
await invalidate();
This reloads data for the /products page, even if you are on a different page.
Svelte
import { invalidate } from '$app/navigation';

// Reload data for a specific route
await invalidate('/products');
This reloads data for a URL with query parameters, useful for dynamic data.
Svelte
import { invalidate } from '$app/navigation';

// Reload data for a specific URL with query
await invalidate('/search?query=svelte');
Sample Program

This simple Svelte component shows a button that, when clicked, increases a count and reloads the current page's data using invalidate(). The count updates immediately, simulating fresh data.

Svelte
<script>
  import { invalidate } from '$app/navigation';
  let count = 0;

  async function refreshData() {
    // Simulate data change
    count += 1;
    // Reload current page data
    await invalidate();
  }
</script>

<button on:click={refreshData} aria-label="Refresh data">Refresh Data</button>
<p>Data refresh count: {count}</p>
OutputSuccess
Important Notes

Use invalidate() to keep your app's data up to date without a full page reload.

Invalidation works well with SvelteKit's load functions that fetch data.

Remember to use await with invalidate() to wait for data to reload before continuing.

Summary

Invalidation reloads data for a route or page to keep information fresh.

Use invalidate() from $app/navigation to trigger reloads.

This helps your app show the latest data after changes or navigation.