Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

305
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda