Coder Social home page Coder Social logo

sveltestack / svelte-query Goto Github PK

View Code? Open in Web Editor NEW
810.0 17.0 31.0 2.22 MB

Performant and powerful remote data synchronization for Svelte

Home Page: https://sveltequery.vercel.app

License: MIT License

JavaScript 1.97% Svelte 12.63% TypeScript 85.41%

svelte-query's Introduction

Hooks for managing, caching and syncing asynchronous and remote data in Svelte

This package has been migrated to the TanStack Query repo.

You can install it with npm install @tanstack/svelte-query

Visit tanstack.com for docs, guides, API and more!

Quick Features

  • Transport/protocol/backend agnostic data fetching (REST, GraphQL, promises, whatever!)
  • Auto Caching + Refetching (stale-while-revalidate, Window Refocus, Polling/Realtime)
  • Parallel + Dependent Queries
  • Mutations + Reactive Query Refetching
  • Multi-layer Cache + Automatic Garbage Collection
  • Paginated + Cursor-based Queries
  • Load-More + Infinite Scroll Queries w/ Scroll Recovery
  • Request Cancellation

Contributing

PRs are welcome! You noticed a bug, a possible improvement or whatever? Any help is always appreciated, so don't hesitate opening one!

Be sure to check out the contributing guidelines to fasten up the merging process.

Get started (Devs)

git clone [email protected]:SvelteStack/svelte-query.git
cd svelte-query
yarn
yarn storybook

Running Storybook

cd storybook
yarn
yarn start

Running the tests

yarn test

Running the Docs

cd docs
yarn
yarn build
yarn start

http://localhost:3000

Build

yarn build

svelte-query's People

Contributors

amen-souissi avatar basaran avatar benmccann avatar frederikhors avatar lxy-yz avatar nyanpasu avatar somaticit avatar tannerlinsley avatar tomradford avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

svelte-query's Issues

Hydration import bug

import { Hydrate } from '@sveltestack/svelte-query/hydration'

@sveltestack/svelte-query/hydration -> cannot be found

@sveltestack/svelte-query -> can be found and works as intended

svelte-query randomly runs the query server-side, and returns an empty result with 'success' status

I have this confusing issue with svelte-query 1.6.0, @sveltejs/kit 1.0.0-next.295, and svelte 3.46.4.

Occasionally, svelte-query will seemingly at random run the query server-side, and returns an empty result with 'success' status.

This query usually works, and if this error happens, I can just open the URL in a new tab and it works fine.

Error:

500
Cannot read property 'muxVideo' of null
TypeError: Cannot read property 'muxVideo' of null
    at [slug].svelte:98:63
    at Object.$$render (/Users/ben/dev/my-project/node_modules/svelte/internal/index.js:1745:22)
    at Object.default (root.svelte:50:47)
    at Object.default (/src/routes/__layout.svelte:187:36)
    at eval (/node_modules/@sveltestack/svelte-query/svelte/queryClientProvider/QueryClientProvider.svelte:38:41)
    at Object.$$render (/Users/ben/dev/my-project/node_modules/svelte/internal/index.js:1745:22)
    at __layout.svelte:106:29
    at Object.$$render (/Users/ben/dev/my-project/node_modules/svelte/internal/index.js:1745:22)
    at root.svelte:38:45
    at $$render (/Users/ben/dev/my-project/node_modules/svelte/internal/index.js:1745:22)

If I log the query result, I get this in the backend logs:

[watch:svelte] {
[watch:svelte]   status: 'success',
[watch:svelte]   isLoading: false,
[watch:svelte]   isSuccess: true,
[watch:svelte]   isError: false,
[watch:svelte]   isIdle: false,
[watch:svelte]   data: { getTranscript: null },
[watch:svelte]   dataUpdatedAt: 1647253771588,
[watch:svelte]   error: null,
[watch:svelte]   errorUpdatedAt: 0,
[watch:svelte]   failureCount: 0,
[watch:svelte]   isFetched: true,
[watch:svelte]   isFetchedAfterMount: false,
[watch:svelte]   isFetching: false,
[watch:svelte]   isRefetching: false,
[watch:svelte]   isLoadingError: false,
[watch:svelte]   isPlaceholderData: false,
[watch:svelte]   isPreviousData: false,
[watch:svelte]   isRefetchError: false,
[watch:svelte]   isStale: false,
[watch:svelte]   refetch: [Function: bound refetch],
[watch:svelte]   remove: [Function: bound remove]
[watch:svelte] }

My component:

<script context="module">
  /**
   * @type {import('@sveltejs/kit').Load}
   */
  export async function load({ params, fetch, session, context }) {
    return {
      props: {
        slug: `${params.slug}`
      }
    };
  }
</script>

<script>
  // deps
  import '$lib/polyfills';
  import { setContext, getContext } from 'svelte';
  import { writable } from 'svelte/store';
  import { useQuery, useInfiniteQuery } from '@sveltestack/svelte-query';

  // queries
  import { TranscriptBySlugDocument } from '$lib/graphql/queries/types/transcripts';

  export let slug;

  const graphQLClient = getContext('graphql-client');

  let params = writable({ slug });
  setContext('params', params);
  $: $params.slug = slug;

  const getTranscript = async () => {
    return await $graphQLClient.request(TranscriptBySlugDocument, { slug: $params.slug });
  };

  const transcriptQuery = useQuery('transcriptQuery', getTranscript, {
    enabled: false
  });

  $: if ($graphQLClient?.fetchOptions?.headers?.['X-Auth-Token'] !== undefined) {
    transcriptQuery.setEnabled(true);
  }
  setContext('transcriptQuery', transcriptQuery);

  $: console.log($transcriptQuery)
</script>

<div class="grid grid-cols-12 gap-3 leading-6 text-gray-700">
  <div class="col-span-4 p-3 leading-6 text-gray-700">
    {#if $transcriptQuery.isLoading || $transcriptQuery.isIdle}
      <span>Loading..</span>
    {:else if $transcriptQuery.isSuccess}
      <div class="video-container" style="min-height: {videoContainerHeight}">
        <TranscriptVideo
          videoId={$transcriptQuery.data.getTranscript.muxVideo.playbackId}
          playerType='hls' />
      </div>
    {:else}
      <span>Error loading video</span>
    {/if}
  </div>
</div>

__layout.svelte:

<script>
  const graphQLClientStore = writable(graphQLClient);
  fetchToken();
  setContext('graphql-client', graphQLClientStore);

  async function fetchToken() {
    // XXX: Temp workaround due to:
    // https://github.com/sveltejs/kit/issues/1198
    //
    // Also see:
    // https://github.com/sveltejs/kit/issues/696
    // https://github.com/sveltejs/kit/issues/672
    //
    // Until this is resolved, useQueryClient cannot
    // be used because we need to reactively update
    // the client with the token after the app has
    // initialised. useQueryClient doesn't allow this
    const userAuth = await fetch('/api/auth/user');
    const tokens = await userAuth.json();
    const jwt = tokens.jwt;

    $graphQLClientStore.setFetchOptions({
      headers: {
        'X-Auth-Token': jwt
      }
    });

    // Trigger reactive update
    $graphQLClientStore = $graphQLClientStore;
  }

  onMount(async () => {
    fetchToken();
  });
</script>

broadcast-channel required in sapper/webpack build

Hi,

I have a project using sapper + webpack and svelte-query in version 1.4.1 which works fine.

I tried to upgrade svelte-query to 1.6.0 but it does not build anymore.

I reproduced the issue by starting a new project from the sapper template and just adding the QueryClient in _layout.svelte

When I npm run build I get:

ERROR in ./node_modules/@sveltestack/svelte-query/svelte/queryCore/broadcastQueryClient-experimental/index.js
Module not found: Error: Can't resolve 'broadcast-channel' in '/home/uvba7442/dev/misc/svelte-query-test/node_modules/@sveltestack/svelte-query/svelte/queryCore/broadcastQueryClient-experimental'
 @ ./node_modules/@sveltestack/svelte-query/svelte/queryCore/broadcastQueryClient-experimental/index.js 3:39-66
 @ ./node_modules/@sveltestack/svelte-query/svelte/queryCore/index.js
 @ ./node_modules/@sveltestack/svelte-query/svelte/index.js
 @ ./src/routes/_layout.svelte
 @ ./src/node_modules/@sapper/internal/manifest-client.mjs
 @ ./src/node_modules/@sapper/app.mjs
 @ ./src/client.js
> Encountered errors while building app

if I npm add broadcast-channel I get errors like Error: Can't resolve 'fs' in '/.../node_modules/broadcast-channel/dist/esnode/methods' instead.

I suppose that I am missing something in the webpack config, but maybe I should rather migrate to svelte-kit instead ?

Is there something to do in the build config to make it ignore the BroadcastQueryClient when it is not used ?

Allow passing queryClient in options instead of taking it from the context

We have a legacy AngularJS 1.x web app which is being converted to Svelte over time, and would like to start using svelte-query here, both inside Svelte code and in some of the old Angular code too, and have them share the same QueryClient.

The main issue I'm having is that the only way for the various functions to get the query client is through useQueryClient, which depends on Svelte context.

I think this could be solved fairly easily if the various functions that call useQueryClient were able to get the client from the options object. Something like const client: QueryClient = options.queryClient ?? useQueryClient(). The only place I've seen where some design decision would need to be made is with useIsFetching, which doesn't take an options object.

What do you think about a change like this? I'm happy to put together the PR if you're ok with it. Thanks!

queryKeyHashFn not working correctly?

Hey again :)

I believe queryClient.setQueryData doesnt use the queryKeyHashFn I supplied, and therefore the updater I'm passing receives undefined for the current cached value argument.

I recently added queryKeyHashFn, and now when using queryClient.setQueryData my updater always receives undefined.

Could you please take a look?

Thank you

keepPreviousData doesn't work with this code

Using the below code keepPreviousData doesn't work.

<script lang="ts">
	import { useQuery } from '@sveltestack/svelte-query';

	import { Condition } from '$lib/common';
	import { service, playerListKey } from '$lib/usecases/player';

	const PAGINATION = {
		DEFAULT: {
			after: '',
			before: '',
			first: 15,
			last: 0,
			orderBy: [{ field: 'id', desc: true }]
		}
	};

	export let refetchEnabled = false;
	export let condition = Condition.create();
	export let pagination = PAGINATION.DEFAULT;

	$: players = useQuery(
		[playerListKey, pagination, condition],
		async () => await service.playerList({ pagination, condition }).response,
		{ keepPreviousData: true }
	);

	$: players.updateOptions({ refetchOnWindowFocus: refetchEnabled });

	function previousPage() {
		pagination = {
			...pagination,
			after: '',
			before: $players.data.pageInfo.startCursor,
			first: 0,
			last: PAGINATION.DEFAULT.first
		};
	}

	function nextPage() {
		pagination = {
			...pagination,
			after: $players.data.pageInfo.endCursor,
			before: '',
			first: PAGINATION.DEFAULT.first,
			last: 0
		};
	}
</script>

<div>
	<button on:click={previousPage}>Next</button>
	<button on:click={nextPage}>Previous</button>
</div>

{#if $players.isLoading}
	Loading...
{:else if $players.isError}
	$players.error
{:else if $players.data}
	<ul>
		{#each $players.data.players as player (player.id)}
			<li><span>{player.name}</span></li>
		{:else}
			No players...
		{/each}
	</ul>
{/if}

Why?

Am I wrong using it?

Expected prop defaultOptions

Getting warning for, was created without expected prop 'defaultOptions'.

Could not find info in the docs to remove this.

Still issues with broadcast-channel dependency and svelte-kit

@amen-souissi @benmccann I tried 1.4.1 now.

We still have a problem with broadcast-channel if I remove these lines from svelte.config.js:

vite: {
  optimizeDeps: {
    include: ['broadcast-channel']
  },
}

This is the log:

1:22:06 AM [vite] Error when evaluating SSR module /node_modules/broadcast-channel/dist/es/method-chooser.js:
ReferenceError: require is not defined
    at eval (/node_modules/broadcast-channel/dist/es/method-chooser.js:26:20)
    at instantiateModule (C:\kit\node_modules\vite\dist\node\chunks\dep-e9a16784.js:68197:166)

Do you have any idea?

Maybe this is related to "type": "module" in package.json which is the default in a new SvelteKit project, right?

Add Vite example

It would be nice if there would be any reference on how to use svelte-query with Vite.

Is there a way to getQueryData() with one key only?

I'm using the code from the docs: https://sveltequery.vercel.app/guides/placeholder-query-data#placeholder-data-from-cache:

const result = useQuery(["blogPost", blogPostId], () => fetch("/blogPosts"), {
  placeholderData: () => {
    // Use the smaller/preview version of the blogPost from the 'blogPosts' query as the placeholder data for this blogPost query
    return queryClient
      .getQueryData("blogPosts")
      ?.find((d) => d.id === blogPostId);
  },
});

My problem is I'm caching blogPosts along with pagination info, something like:

let pagination = { page: 1, limit: 20 };

$: posts = useQuery(
  ["blogPosts", pagination],
  async () => await fetchPosts({ pagination })
);

Is there a way I can use placeholderData with .getQueryData("blogPosts") key only (without pagination)?

[Vite] Function called outside of component initialization

Edit : my example is stupid, it lacks a provider. I will have a better example when I get home

Hi, first let me start by saying that the library is great. I've been using it in classic svelte projects and it works like a charm.
This week I started working on a Vite project and... well this time, it's not really working.

When I call useQuery in component initialization, it just throws "Function called outside component initialization"

How to reproduce:

git clone https://github.com/geoffreymugnier/vite-svelte-query-crash.git
cd vite-svelte-query-crash
npm i
npm run dev

Repo : https://github.com/geoffreymugnier/vite-svelte-query-crash
Am I doing something wrong ?

Does the caching even work or am I missing something?

Hello,

I tried to run a simple query:

const url = 'https://jsonplaceholder.typicode.com/users';
const queryResult = useQuery('users', () => fetch(url).then((res) => res.json()))

But everytime I reload or switch page back and forth, the data looks to be refetched everytime.
On the devtools network tab I'm expecting (disk cache) being used, but it doesn't.

I tried:

refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
retry: false,
staleTime: 3600000,
refetchInterval: 3000000

am I missing something?

Using svelte-query with jest - Cannot find module '../../src/methods/node.js'

When running a test file which imports from svelte-query I get

Cannot find module '../../src/methods/node.js' from 'node_modules/@sveltestack/svelte-query/dist/index.js'
Require stack:
node_modules/@sveltestack/svelte-query/dist/index.js
src/App.test.ts
at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:311:11)

Project to reproduce the issue here

The import in App.test.ts appears to be causing the problem.

I have placed svelte-query in devDependencies as suggested in another issue but still have the same problem.

Something similar to cache-first for Apollo and Urql?

Coming from Apollo or Urql I would like to know if there is a way to mimic (or improve) the behavior of policies like "cache-first":

(the default) prefers cached results and falls back to sending an API request when no prior result is cached: https://formidable.com/open-source/urql/docs/basics/document-caching/#request-policies.

An example: I already have user data queried in Home page then I navigate to User page and I wanna say to svelte-query to NOT query again my user data because I already have them in cache (with Infinite stale).

Am I wrong to want this?

I tried with the enabled option but obviously if navigate on the user's page before the Home page the query does not start at all.

How to do?

How to test svelte-query using jest / svelte-testing-library

Hello,
I have setup up an application using this: https://github.com/mihar-22/svelte-jester#typescript
So i got working jest with sveltekit, everything works fine when i render simple page.

But my problem is when i try to add svelte-query. I mocked http requestes using msw, but it seems like the useQuery is in never ending 'loading' state. No errors, no nothing, always loading.

Do i need to do something to make the query works? Maybe my render using svelte-testing-library is not picking up on subscription changes from the query?

I tried adding tick() function from svelte, but it didnt helped.

Would be really greatfull for some help.

Reactive Query Key Change Detection ?

Hi,

I'm probably missing a detail but I can't use the reactivity of Svelte for queryKey provided to useQuery().

Here is a very basic example of a search box that is not working :

<script>
  import { useQuery } from "@sveltestack/svelte-query";
  import debounce from "debounce";

  let search = "";

  function getTest({ queryKey }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(`Response for queryKey ${JSON.stringify(queryKey)}`);
      }, 500);
    });
  }

  const query = useQuery(["test", search], getTest);

  const handleSearch = debounce(event => {
    search = event.target.value;
  }, 200);
</script>

<input type="search" placeholder="Search" on:input={handleSearch}>

See on codesanbox

NOTE: the same logic work perfectly with react-query

Thank for this awesome framwork 💚
...and sorry for my english (Google trad)

Calling .slice throws error: "Cannot read properties of undefined (reading 'slice')" Even if defined.

Doing {#each $queryResult.data.slice(0, 9) as item} throws error: Cannot read properties of undefined (reading 'slice') Even if defined.

This is impossible because I have all my checks in my markup, so it renders the each only when there is data, at least I know for fact that this could never happen in react js, to have it undefined at his point, so this seems to me like a bug or am I missing something?

Are we really using the original .svelte files?

I know that when in package.json there is the "svelte": "svelte/index.js" field the Svelte project that uses that package must use the original source code and not the final bundle in dist.

I tried to manually delete the dist folder from node_modules/@sveltestack/svelte-query and the project doesn't start anymore because it wants that folder.

Is this right or are we doing something wrong?

I would like to use the .svelte files directly and then build them in my build process. This is one of the very tasty things about Svelte.

Am I wrong?

Vite project not starting in development mode without broadcast-channel installed

After updating to release 1.5.0 I needed to install broadcast-channel manually to get my project running in development mode. The production bundle, on the other hand, can be created without the dependency without any problems and works perfectly. I'm not using the broadcastQueryClient in my project. I use [email protected]. Of course I can install broadcast-channel but I thought it would not be needed as of release 1.5.0. Or did I understand the release notes wrong? Do I have to make certain settings in vite for it to work? I have already excluded @sveltestack/svelte-query in the vite.config.js.

[vite] Internal server error: Failed to resolve import "broadcast-channel" from "node_modules/@sveltestack/svelte-query/svelte/queryCore/broadcastQueryClient-experimental/index.js". Does the file exist?
Plugin: vite:import-analysis
File: /Users/XXXXX/node_modules/@sveltestack/svelte-query/svelte/queryCore/broadcastQueryClient-experimental/index.js
1  |  import '../core';
2  |  export async function broadcastQueryClient({ queryClient, broadcastChannel = 'svelte-query', }) {
3  |      const { BroadcastChannel } = await import('broadcast-channel');
   |                                                ^
4  |      let transaction = false;
5  |      const tx = (cb) => {

unsupported engine warning

Hey awesome library so far. Iam just wondering why there is a "Unsupported engine" warning when installing with npm v7. Is there a reason why I should use yarn instead of npm ?
image

asyncThrottle from createAsyncStoragePersistor-experimental is not throttling

The asyncThrottle function used by createAsyncStoragePersistor is not working as expected.

Behaviour:
It will just delay the persistClient function with throttleTime but won't limit the number of concurrent call to 1.

Result:
The data is not persisted correctly when multiple useQuery are used simultaneously.

Solution:
I used the lodash throttle function instead and it is working like a charm. The persistence is working great as well.

Cannot find module '../../src/methods/node.js'

I'm struggling to get the basic examples of svelte-query to work. A clean sapper or svelte kit app results in this when I import anything from @sveltestack/svelte-query. Perhaps some issue with es6 modules vs commonjs but I am not experienced enough to figure out more.

e.g. import { QueryClient, QueryClientProvider } from '@sveltestack/svelte-query'

results in

yarn run v1.22.10
warning package.json: No license field
$ sapper dev
• server
@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to true, as the next major version will default this option to true.
'QueryClient' and 'QueryClientProvider' are imported from external module '@sveltestack/svelte-query' but never used
• client
@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to true, as the next major version will default this option to true.
node:internal/modules/cjs/loader:926
  throw err;
  ^

Error: Cannot find module '../../src/methods/node.js'
Require stack:
- ***/node_modules/@sveltestack/svelte-query/dist/index.js
- ***/__sapper__/dev/server/server.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:923:15)
    at Function.Module._load (node:internal/modules/cjs/loader:768:27)
    at Module.require (node:internal/modules/cjs/loader:995:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at ***/node_modules/@sveltestack/svelte-query/dist/index.js:3061:24
    at ***/node_modules/@sveltestack/svelte-query/dist/index.js:2:68
    at Object.<anonymous> (***/node_modules/@sveltestack/svelte-query/dist/index.js:5:2)
    at Module._compile (node:internal/modules/cjs/loader:1091:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1120:10)
    at Module.load (node:internal/modules/cjs/loader:971:32) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '***/@sveltestack/svelte-query/dist/index.js',
    '***/__sapper__/dev/server/server.js'
  ]
}
> Server crashed
• service worker
node --version
v15.10.0

Why this line in package.json?

Can I ask you why this line?

"npm": "use yarn instead of npm."

  • package.json:
    "npm": "use yarn instead of npm."

The new Svelte Kit init template starter comes with the file .npmrc with engine-strict=true inside which prevents installation.

I'm using npm install -DE @sveltestack/svelte-query command.

Upgrade / remove dependencies

As you can see there are a lot of dependencies to upgrade.

Are you sure about fs? Do we need it?

Do we need babel in root?

image

[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query...

I'm using for the first time svelte-query and for the first time too svelte-kit.

I'm having these warnings/errors in console everytime I start my project:

[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/queryClientProvider/QueryClientProvider.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/query/Query.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/infiniteQuery/InfiniteQuery.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/queries/Queries.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/isMutating/IsMutating.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/isFetching/IsFetching.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/hydration/Hydrate.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/mutation/Mutation.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/queryClientProvider/QueryClientProvider.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/query/Query.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/infiniteQuery/InfiniteQuery.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/queries/Queries.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/isFetching/IsFetching.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/isMutating/IsMutating.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/mutation/Mutation.svelte.
[vite] Failed to load source map for /node_modules/@sveltestack/svelte-query/svelte/hydration/Hydrate.svelte.

Why?

Cache not working as expected

This video shows 2 pages where both include the Threads component. The issue is that on first navigation the cache from the initial page doesn't seem to get used. If you go back though and then click a thread again, the list cache seem to get used.

For context, I am using SvelteKit

CleanShot.2021-11-04.at.00.37.27.mp4

Threads.svelte

<script>
  import ListThread from "./ListThread.svelte";
  import { useQuery } from "@sveltestack/svelte-query";

  const getThreads = async () => {
    return fetch("/gmail/email")
      .then((res) => res.json())
      .then((res) => res);
  };

  const threadsResult = useQuery("threads", getThreads);
</script>

{#if $threadsResult.data}
  <ul class="threads divide-y">
    {#each $threadsResult.data.emails?.data.threads ?? [] as thread (thread.id)}
      <ListThread {thread} />
    {/each}
  </ul>
{:else if $threadsResult.error}
  <p>An error occurred!</p>
{:else if $threadsResult.isLoading}
  <p>...waiting</p>
{/if}

Am I misunderstanding something here or is something broken?

broadcast-channel error with SvelteKit

I get broadcast-channel error with 1.6 and SvelteKit .311

[plugin:vite:import-analysis] Failed to resolve import "broadcast-channel" from "node_modules/@sveltestack/svelte-query/svelte/queryCore/broadcastQueryClient-experimental/index.js". Does the file exist?
[/Users/finn/Documents/Projects/wip/node_modules/@sveltestack/svelte-query/svelte/queryCore/broadcastQueryClient-experimental/index.js:3:47]()
1  |  import '../core';
2  |  export async function broadcastQueryClient({ queryClient, broadcastChannel = 'svelte-query', }) {
3  |      const { BroadcastChannel } = await import('broadcast-channel');
   |                                                ^
4  |      let transaction = false;
5  |      const tx = (cb) => {

Hello,

A new version (v1.5.0) of this library has been published today.
This version makes broadcast-channel an optional dependency.
This should fix all problems with svelte-kit.

If you need to use the experimental broadcastQueryClient, you now need to install it manually (see: broadcastQueryClient).

If you still encounter issues with v1.5.0. Please open a new issue.

Originally posted by @SomaticIT in #39 (comment)

Clarify: “ violate the rules of hooks”

https://sveltequery.vercel.app/guides/parallel-queries

Dynamic Parallel Queries with useQueries

If the number of queries you need to execute is changing from render to render, you cannot use manual querying since that would violate the rules of hooks. Instead, Svelte Query provides a useQueries hook, which you can use to dynamically execute as many queries in parallel as you'd like.

I am verify familiar with the concept of hooks and all their pitfalls in React, but this is the first time I read something mentioning rules of hooks in Svelte.

Can you please elaborate what can go one calls useQuery conditionally?

Queries always maked as successful even when error occured

Hello,

Thanks a lot for the project and the work put into it, really appreciate having a port of react-query in the Svelte ecosystem!

I notice recently trying to implement error handling logic that queries never really "fail", here an example based on the simple example:
https://codesandbox.io/s/optimistic-lumiere-j08we?file=/src/Simple.svelte:0-65

As you can see, I'm hitting a random URL on GitHub which will return a 404 but even when the query fails, $queryResult.error is null.

I also tried on a blank Svelte project and the same issue occurs.

I'm going to investigate a little more in the project to figure where exactly the problem lies.

Thanks again for your work

Unable to access children of response data when using Sapper

<script context="module">
  export async function preload({ params }) {

    const res = await this.fetch('example.com/id1234.json');
    const resJSON = await res.json();

    return { resJSON };
  }
</script>

Then later in the code...

const queryResult = useQuery('characterData', async () => {
  const data = await axios.get('example.com/id1234.json')
  return data
},{refetchInterval: 30000, initialData: menuData, refetchIntervalInBackground: false, notifyOnChangeProps: ['data', 'error']})

Then...

{#if $queryResult}
  {JSON.stringify($queryResult.data.characters)}
{/if}

will result in a the initial data showing for a split second and then it showing 'undefined'. What's weird is that if I just output the entire $queryResult.data it will not show undefined, but the entire object. I hope this makes sense.

EDIT: I found the issue! I needed to return { data }; instead of return data from axios, 🤦‍♂️

Custom hooks?

I'm coming from the React SWR, where I can create a hook like this:

function useUser (id) {
  const { data, error } = useSWR(`/api/user/${id}`, fetcher)

  return {
    user: data,
    isLoading: !error && !data,
    isError: error
  }
}

and then use it in my components like this:

function Avatar ({ id }) {
  const { user, isLoading, isError } = useUser(id)

  if (isLoading) return <Spinner />
  if (isError) return <Error />
  return <img src={user.avatar} />
}

Is something like the possible with Svelte Query? I tried a manual subscription to the useQuery, which doesn't seem to trigger the re-render though.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.