Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

307
Vistas
Svelte: Reactive declaration does not work when passing a declared function

Problem

I created a reactive variable to sort an array when a state variable has changed. It does work if I declare the sort function directly as a callback, but not if I pass an already declared function.

Code

So this is the code which does not work:

  const sortSongs = (a, b) => {
        const [option, direction] = sortOption.split("-");
        const itemA = a[option == "Song" ? "title" : "artist"].toLowerCase();
        const itemB = b[option == "Song" ? "title" : "artist"].toLowerCase();

        if (itemA < itemB) {
          return direction == "up" ? 1 : -1;
        }

        if (itemA > itemB) {
          return direction == "up" ? -1 : 1;
        }

    return 0;
  };

  $: filteredSongs =
    lessons
      ?.sort(sortSongs)
      .filter(lesson => lesson.title?.toLowerCase().includes(value)) || [];

And this the one who does work:

  $: filteredSongs =
    lessons
      ?.sort((a, b) => {
        const [option, direction] = sortOption.split("-");
        const itemA = a[option == "Song" ? "title" : "artist"].toLowerCase();
        const itemB = b[option == "Song" ? "title" : "artist"].toLowerCase();

        if (itemA < itemB) {
          return direction == "up" ? 1 : -1;
        }

        if (itemA > itemB) {
          return direction == "up" ? -1 : 1;
        }

        return 0;
      })
      .filter(lesson => lesson.title?.toLowerCase().includes(value)) || [];

Confusion

So shouldn't both be working? Why does it make a difference where I declare the function? Here is a REPL to see this in action. The red songs got the not-working code, while the green ones have the working one.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You expect $: filteredSongs to reevaluate when sortOption changes, but when you pass the function reference .sort(sortSongs), sortOption is 'hidden' inside the function and not directly related to the reactive statement anymore. It's mentioned in the docs here in the second paragraph

Only values which directly appear within the $: block will become dependencies of the reactive statement

A quick and dirty solution would be to pass sortOption as a parameter

?.sort(sortSongs, sortOption)

.sort() only expects the compare function as argument, so sortOption will be ignored, but is again a dependency because inside the $: block again

This would be a clearer alternative without calling .sort() with a 'redundant' argument

let lessons = [];
...

const sortSongs = (songs, sortOption) => {
        return songs.sort((a,b) => {
            const [option, direction] = sortOption.split("-");
            const itemA = a[option == "Song" ? "title" : "artist"].toLowerCase();
            const itemB = b[option == "Song" ? "title" : "artist"].toLowerCase();

            if (itemA < itemB) {
                return direction == "up" ? 1 : -1;
            }

            if (itemA > itemB) {
                return direction == "up" ? -1 : 1;
            }

            return 0;
        })     
    };

    $: filteredSongs =
        sortSongs(lessons, sortOption)
        .filter(lesson => lesson.title?.toLowerCase().includes(value));
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda