Skip to content

Commit

Permalink
feat(svelte-5-adapter): require options to be passed as function (#7804)
Browse files Browse the repository at this point in the history
* fix(svelte-5-adapter): Require options to be passed as function

* More fixes

* More fixes

* Update examples
  • Loading branch information
lachlancollins committed Jul 31, 2024
1 parent 3b2a6e6 commit d2660a5
Show file tree
Hide file tree
Showing 44 changed files with 164 additions and 200 deletions.
4 changes: 2 additions & 2 deletions examples/svelte/basic/src/lib/Post.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
const { postId }: { postId: number } = $props()
const post = createQuery<Post>({
const post = createQuery<Post>(() => ({
queryKey: ['post', postId],
queryFn: () => getPostById(postId),
})
}))
</script>

<div>
Expand Down
4 changes: 2 additions & 2 deletions examples/svelte/basic/src/lib/Posts.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
const posts = createQuery<
{ id: number; title: string; body: string }[],
Error
>({
>(() => ({
queryKey: ['posts', limit],
queryFn: () => getPosts(limit),
})
}))
</script>

<div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
const fetchPlanets = async ({ pageParam = 1 }) =>
await fetch(`${endPoint}/planets/?page=${pageParam}`).then((r) => r.json())
const query = createInfiniteQuery({
const query = createInfiniteQuery(() => ({
queryKey: ['planets'],
queryFn: ({ pageParam }) => fetchPlanets({ pageParam }),
initialPageParam: 1,
Expand All @@ -20,7 +20,7 @@
}
return undefined
},
})
}))
</script>

{#if query.isPending}
Expand Down
4 changes: 2 additions & 2 deletions examples/svelte/optimistic-updates/src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@
}),
}).then((res) => res.json())
const todos = createQuery<Todos>({
const todos = createQuery<Todos>(() => ({
queryKey: ['optimistic'],
queryFn: fetchTodos,
})
}))
const addTodoMutation = createMutation({
mutationFn: createTodo,
Expand Down
8 changes: 7 additions & 1 deletion examples/svelte/playground/src/routes/AddTodo.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@
() => {
if (Math.random() < errorRate.value) {
return reject(
new Error(JSON.stringify({ postTodo: { name, notes } }, null, 2)),
new Error(
JSON.stringify(
{ postTodo: { name: $state.snapshot(name), notes } },
null,
2,
),
),
)
}
const todo = { name, notes, id: id.value }
Expand Down
6 changes: 3 additions & 3 deletions examples/svelte/playground/src/routes/EditTodo.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
}
list.value = list.value.map((d) => {
if (d.id === todo.id) {
return todo
return $state.snapshot(todo)
}
return d
})
Expand All @@ -67,11 +67,11 @@
})
}
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['todo', { id: editingIndex.value }],
queryFn: () => fetchTodoById({ id: editingIndex.value || 0 }),
enabled: editingIndex.value !== null,
})
}))
const saveMutation = createMutation({
mutationFn: patchTodo,
Expand Down
4 changes: 2 additions & 2 deletions examples/svelte/simple/src/lib/Simple.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
forks_count: number
}
const query = createQuery<Repo>({
const query = createQuery<Repo>(() => ({
queryKey: ['repoData'],
queryFn: async () =>
await fetch('https://api.github.com/repos/TanStack/query').then((r) =>
r.json(),
),
})
}))
</script>

<h1>Simple</h1>
Expand Down
4 changes: 2 additions & 2 deletions examples/svelte/ssr/src/lib/Post.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
const { postId }: { postId: number } = $props()
const post = createQuery<Post>({
const post = createQuery<Post>(() => ({
queryKey: ['post', postId],
queryFn: () => api().getPostById(postId),
})
}))
</script>

<div>
Expand Down
4 changes: 2 additions & 2 deletions examples/svelte/ssr/src/lib/Posts.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
const posts = createQuery<
{ id: number; title: string; body: string }[],
Error
>({
>(() => ({
queryKey: ['posts', limit],
queryFn: () => api().getPosts(limit),
})
}))
</script>

<div>
Expand Down
4 changes: 2 additions & 2 deletions examples/svelte/star-wars/src/routes/characters/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
return await res.json()
}
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['characters'],
queryFn: getCharacters,
})
}))
</script>

{#if query.status === 'pending'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
return await res.json()
}
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['character', data.params.characterId],
queryFn: getCharacter,
})
}))
</script>

{#if query.status === 'pending'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
return await res.json()
}
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['film', filmId],
queryFn: getFilm,
})
}))
</script>

{#if query.status === 'success'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
return await res.json()
}
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['homeworld', homeworldId],
queryFn: getHomeworld,
})
}))
</script>

{#if query.status === 'success'}
Expand Down
4 changes: 2 additions & 2 deletions examples/svelte/star-wars/src/routes/films/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
return await res.json()
}
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['films'],
queryFn: getFilms,
})
}))
</script>

{#if query.status === 'pending'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
return await res.json()
}
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['film', data.params.filmId],
queryFn: getFilm,
})
}))
</script>

{#if query.status === 'pending'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
return await res.json()
}
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['character', characterId],
queryFn: getCharacter,
})
}))
</script>

{#if query.status === 'success'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
let { states }: { states: Array<string> } = $props()
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['test'],
queryFn: async () => {
states.push('fetching')
await sleep(5)
states.push('fetched')
return 'fetched'
},
})
}))
</script>

<div>{query.data}</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
fetched: boolean
} = $props()
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['test'],
queryFn: async () => {
fetched = true
Expand All @@ -21,7 +21,7 @@
},
staleTime: Infinity,
})
}))
$effect(() => {
states.value = [...untrack(() => states.value), $state.snapshot(query)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
let { states }: { states: { value: Array<StatusResult<string>> } } = $props()
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['test'],
queryFn: async () => {
await sleep(5)
Expand All @@ -17,7 +17,7 @@
// make sure that initial data is older than the hydration data
// otherwise initialData would be newer and takes precedence
initialDataUpdatedAt: 1,
})
}))
$effect(() => {
states.value = [...untrack(() => states.value), $state.snapshot(query)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
import { createQuery } from '@tanstack/svelte-query'
import { sleep } from '../utils.svelte'
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['test'],
queryFn: async () => {
await sleep(5)
return 'fetched'
},
})
}))
</script>

<div>{query.data}</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
import { createQuery } from '@tanstack/svelte-query'
import { sleep } from '../utils.svelte'
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['test'],
queryFn: async () => {
await sleep(5)
return 'fetched'
},
})
}))
</script>

<div>{query.data}</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
let { states }: { states: { value: Array<StatusResult<string>> } } = $props()
const query = createQuery({
const query = createQuery(() => ({
queryKey: ['test'],
queryFn: async () => {
await sleep(5)
return 'fetched'
},
})
}))
$effect(() => {
states.value = [...untrack(() => states.value), $state.snapshot(query)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
let { states }: { states: { value: Array<StatusResult<string>> } } = $props()
const queries = createQueries({
queries: [
queries: () => [
{
queryKey: ['test'],
queryFn: async (): Promise<string> => {
Expand Down
23 changes: 9 additions & 14 deletions packages/svelte-query/src/createBaseQuery.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import { notifyManager } from '@tanstack/query-core'
import { untrack } from 'svelte'
import { useIsRestoring } from './useIsRestoring'
import { useQueryClient } from './useQueryClient'
import type { CreateBaseQueryOptions, CreateBaseQueryResult } from './types'
import type {
CreateBaseQueryOptions,
CreateBaseQueryResult,
FunctionedParams,
} from './types'
import type {
QueryClient,
QueryKey,
Expand All @@ -17,31 +21,22 @@ export function createBaseQuery<
TQueryData,
TQueryKey extends QueryKey,
>(
options: CreateBaseQueryOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
options: FunctionedParams<
CreateBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
>,
Observer: typeof QueryObserver,
queryClient?: QueryClient,
): CreateBaseQueryResult<TData, TError> {
/** Load query client */
const client = useQueryClient(queryClient)
const isRestoring = useIsRestoring()
const optionsStore = typeof options !== 'function' ? () => options : options

/** Creates a store that has the default options applied */
function updateOptions() {
const key = optionsStore().queryKey
const keyFn = typeof key === 'function' ? key : () => key // allow query-key and enable to be a function
const queryKey: TQueryKey = $state.snapshot(keyFn()) as any // remove proxy prevent reactive query in devTools
let tempEnable = optionsStore().enabled
const queryKey: TQueryKey = $state.snapshot(options().queryKey) as any // remove proxy prevent reactive query in devTools
const defaultedOptions = client.defaultQueryOptions({
...optionsStore(),
...options(),
queryKey: queryKey,
enabled: typeof tempEnable == 'function' ? tempEnable() : tempEnable,
})
defaultedOptions._optimisticResults = 'optimistic'
if (isRestoring()) {
Expand Down
Loading

0 comments on commit d2660a5

Please sign in to comment.