Search code examples
svelteindexeddbdexie

Why is only one of my Dexie queries updating in Svelte?


I have a svelte application that uses Dexie for data persistence. In my main component I have a child component that runs two liveQuerys to get the previous fixture and next fixture for a sports team. However, when advancing through time (it's a sports management simulation game) the next fixture updates reactively but the previous fixture doesn't update.

lastFixtures and nextFixtures returns an array of 10 fixtures for that round.

In the filter functions I'm hardcoding the ID for the team I'm using for now, this is a work in progress.


FixtureSummary.svelte

<script>
  import { liveQuery } from 'dexie'
  import { db } from '../../db'
  import { leagueRound } from '../../store'
  let lastFixtures = liveQuery(() =>
    db
      .fixtures
      .get($leagueRound - 1)
  )
  let nextFixtures = liveQuery(() =>
    db
      .fixtures
      .get($leagueRound)
  )
  $: lastFixture = $lastFixtures?.fixtures.filter(f => f.home.id === 15 || f.away.id === 15)[0]
  $: nextFixture = $nextFixtures?.fixtures.filter(f => f.home.id === 15 || f.away.id === 15)[0]
</script>

<div>
  <h3>Last Fixture</h3>
  {#if lastFixture}
    <p>{lastFixture.home.name} {lastFixture.homeGoals} - {lastFixture.awayGoals} {lastFixture.away.name}</p>
  {:else}
  <p>N/A</p>
  {/if}
  <h3>Next Fixture</h3>
  {#if nextFixture}
    <p>{nextFixture.home.name} vs {nextFixture.away.name}</p>
  {:else}
    <p>N/A</p>
  {/if}
</div>

Question: Why does only one of my queries update in the view of my component?


As a secondary question, I tried getting both the previous and next fixtures in one query like so:

liveQuery(() => 
  db
    .fixtures
    .where('id')
    .anyOf([$leagueRound - 1, $leagueRound])
    .toArray()
)

However, that didn't seem to return anything, so any pointers on that would also be much obliged.


Solution

  • If you expect the component to update when the $leagueRound store updates, you'd need to replace let with $: on the liveQuery rows. Also make sure to use the latest version of dexie (currently [email protected] or [email protected]). Other than that, I have no explanation why the anyOf query didn't return any result or that the second query doesn't update.

    If you still have a problem after changing to use $:, please file a new issue on Dexie.js github site and supply a repro for it that is easy to execute (preferably on a site such as codesandbox or similar).