98 Matching Annotations
  1. Oct 2023
  2. Sep 2023
    1. ```svelte

      <script> $: getFirstValue = () => { // here be calculations // that does not fit on one line return result } $: getSecondValue = () => { // here be calculations // that does not fit on one line return result } // will rerun everytime getFirstValue or getSecondValue is updated because of reactivity $: value = getFirstValue() || getSecondValue() </script> <div id="app"> {value} </div>

      ```

    2. if the function declaration is reactive, then Svelte will redeclare the function everytime something within it changes, which makes the function rerun in the markup

      ```svelte

      <script> $: giveMeSomething = () => { //... some code return something } </script> <div id="app"> {giveMeSomething()} </div>

      ```

    1. Runes are an additive feature, but they make a whole bunch of existing concepts obsolete: the difference between let at the top level of a component and everywhere else export let $:, with all its attendant quirks different behaviour between <script> and <script context="module"> the store API, parts of which are genuinely quite complicated the $ store prefix $$props and $$restProps lifecycle functions (things like onMount can just be $effect functions)
    1. ```svelte

      <script> let m = { x: 0, y: 0 }; function handleMousemove(event) { m.x = event.clientX; m.y = event.clientY; } </script> <div on:mousemove={handleMousemove}> The mouse position is {m.x} x {m.y} </div> <style> div { width: 100%; height: 100%; } </style>

      ```

      ```js / React Hook - sample code to capture mouse coordinates/

      import React, { useState, useCallback, useEffect, useRef } from 'react';

      function useEventListener(eventName, handler, element = window) { // Create a ref that stores handler const savedHandler = useRef();

      // Update ref.current value if handler changes. // This allows our effect below to always get latest handler ... // ... without us needing to pass it in effect deps array ... // ... and potentially cause effect to re-run every render. useEffect(() => { savedHandler.current = handler; }, [handler]);

      useEffect(() => { // Make sure element supports addEventListener const isSupported = element && element.addEventListener; if (!isSupported) return;

        // Create event listener that calls handler function stored in ref
        const eventListener = event => savedHandler.current(event);
      
        // Add event listener
        element.addEventListener(eventName, eventListener);
      
        // Remove event listener on cleanup
        return () => {
          element.removeEventListener(eventName, eventListener);
        };
      },
      [eventName, element] // Re-run if eventName or element changes
      

      ); }

      export default function App() { // State for storing mouse coordinates const [coords, setCoords] = useState({ x: 0, y: 0 });

      // Event handler utilizing useCallback ... // ... so that reference never changes. const handler = useCallback( ({ clientX, clientY }) => { // Update coordinates setCoords({ x: clientX, y: clientY }); }, [setCoords] );

      // Add event listener using our hook useEventListener('mousemove', handler);

      return (

      The mouse position is ({coords.x}, {coords.y})

      ); } ```

    1. Otherwise, you can manually call goto instead of history.replaceState is a good way to maintain client-side navigation (no reloads).
    2. I highly recommend using GET forms to implement this as SvelteKit will intercept and retain client-side navigation on form submission. https://kit.svelte.dev/docs/form-actions#get-vs-post Submitting the form will update the URL with the search parameters matching the input names and values.

      ```html

      <form action="/baz"> <label> Query <input name="query"> </label> <label> Sort <input name="sort"> </label> <label> Order <input name="order"> </label> <label> Page <input name="page"> </label> </form>

      ```

    1. ```js let query = new URLSearchParams($page.url.searchParams.toString());

      query.set('word', word);

      goto(?${query.toString()}); ```

      js $page.url.searchParams.set('word',word); goto(`?${$page.url.searchParams.toString()}`);

  3. Aug 2023
    1. SvelteKit will automatically await the fetchPost call before it starts rendering the page, since it’s at the top level. However, it won’t wait for the nested fetchComments call to complete – the page will render and data.streamed.comments will be a promise that will resolve as the request completes. We can show a loading state in the corresponding +page.svelte using Svelte’s await block:

      js export const load: PageServerLoad = () => { return { post: fetchPost(), streamed: { comments: fetchComments() } }; }; ```svelte

      <script lang="ts"> import type { PageData } from './$types'; export let data: PageData; </script> <article> {data.post} </article>

      {#await data.streamed.comments} Loading... {:then value} <br />

        {#each value as comment}
      1. {comment}
      2. {/each}

      {/await} ```

  4. Jul 2023
    1. ```html

      <script> let counter = 0; let evens = 0; $: { if (counter > 10) { break $; } if (counter % 2 === 0) { evens++; } } </script>

      <button on:click={() => (counter++)}> Increment </button>

      Counter: {counter}, evens before 10: {evens}

      ```

  5. Jun 2023