diff --git a/examples/react/algolia/.prettierrc b/examples/react/algolia/.prettierrc
deleted file mode 100644
index 0967ef424b..0000000000
--- a/examples/react/algolia/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/examples/react/algolia/package.json b/examples/react/algolia/package.json
index e2dc6611ae..5125164887 100644
--- a/examples/react/algolia/package.json
+++ b/examples/react/algolia/package.json
@@ -12,15 +12,15 @@
"@algolia/transporter": "4.17.1",
"@tanstack/react-query": "^5.0.0-alpha.38",
"@tanstack/react-query-devtools": "^5.0.0-alpha.38",
- "algoliasearch": "4.17.1"
+ "algoliasearch": "4.17.1",
+ "react": "^18.2.0",
+ "react-dom": "^18.2.0"
},
"devDependencies": {
"@tanstack/eslint-plugin-query": "^5.0.0-alpha.36",
"@types/react": "^18.2.4",
"@types/react-dom": "^18.2.4",
"@vitejs/plugin-react": "^4.0.0",
- "react": "^18.2.0",
- "react-dom": "^18.2.0",
"typescript": "^5.0.4",
"vite": "^4.2.0"
},
diff --git a/examples/react/algolia/src/App.tsx b/examples/react/algolia/src/App.tsx
index 6770f42445..039e66024e 100644
--- a/examples/react/algolia/src/App.tsx
+++ b/examples/react/algolia/src/App.tsx
@@ -1,9 +1,9 @@
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import "./styles.css";
-import Search from "./Search";
+import './styles.css'
+import Search from './Search'
-const queryClient = new QueryClient();
+const queryClient = new QueryClient()
export default function App() {
return (
@@ -13,5 +13,5 @@ export default function App() {
- );
+ )
}
diff --git a/examples/react/algolia/src/Search.tsx b/examples/react/algolia/src/Search.tsx
index 1e9f97dcc9..3755abe5a9 100644
--- a/examples/react/algolia/src/Search.tsx
+++ b/examples/react/algolia/src/Search.tsx
@@ -1,15 +1,15 @@
-import { useState } from "react";
+import { useState } from 'react'
-import SearchResults from "./SearchResults";
+import SearchResults from './SearchResults'
export default function Search() {
- const [query, setQuery] = useState("");
+ const [query, setQuery] = useState('')
const handleOnChange = (event: React.ChangeEvent) => {
- event.preventDefault();
+ event.preventDefault()
// It is recommended to debounce this event in prod
- setQuery(event.target.value);
- };
+ setQuery(event.target.value)
+ }
return (
@@ -20,5 +20,5 @@ export default function Search() {
/>
- );
+ )
}
diff --git a/examples/react/algolia/src/SearchResults.tsx b/examples/react/algolia/src/SearchResults.tsx
index d03fb303d8..59b353a7dd 100644
--- a/examples/react/algolia/src/SearchResults.tsx
+++ b/examples/react/algolia/src/SearchResults.tsx
@@ -1,16 +1,16 @@
-import useAlgolia from "./useAlgolia";
+import useAlgolia from './useAlgolia'
type Product = {
- name: string;
- shortDescription: string;
- salePrice: number;
-};
+ name: string
+ shortDescription: string
+ salePrice: number
+}
type SearchResultsProps = {
- query: string;
-};
+ query: string
+}
-export default function SearchResults({ query = "" }: SearchResultsProps) {
+export default function SearchResults({ query = '' }: SearchResultsProps) {
const {
hits,
isLoading,
@@ -20,17 +20,17 @@ export default function SearchResults({ query = "" }: SearchResultsProps) {
isFetchingNextPage,
fetchNextPage,
} = useAlgolia({
- indexName: "bestbuy",
+ indexName: 'bestbuy',
query,
hitsPerPage: 5,
staleTime: 1000 * 30, // 30s
gcTime: 1000 * 60 * 15, // 15m
enabled: !!query,
- });
+ })
- if (!query) return null;
+ if (!query) return null
- if (isLoading) return Loading...
;
+ if (isLoading) return Loading...
return (
@@ -69,5 +69,5 @@ export default function SearchResults({ query = "" }: SearchResultsProps) {
)}
- );
+ )
}
diff --git a/examples/react/algolia/src/algolia.ts b/examples/react/algolia/src/algolia.ts
index 6cc1ef4972..bc816ac104 100644
--- a/examples/react/algolia/src/algolia.ts
+++ b/examples/react/algolia/src/algolia.ts
@@ -1,17 +1,17 @@
-import algoliasearch from "algoliasearch";
-import { Hit } from "@algolia/client-search";
+import algoliasearch from 'algoliasearch'
+import { Hit } from '@algolia/client-search'
// From Algolia example
// https://github.com/algolia/react-instantsearch
-const ALGOLIA_APP_ID = "latency";
-const ALGOLIA_SEARCH_API_KEY = "6be0576ff61c053d5f9a3225e2a90f76";
+const ALGOLIA_APP_ID = 'latency'
+const ALGOLIA_SEARCH_API_KEY = '6be0576ff61c053d5f9a3225e2a90f76'
type SearchOptions = {
- indexName: string;
- query: string;
- pageParam: number;
- hitsPerPage: number;
-};
+ indexName: string
+ query: string
+ pageParam: number
+ hitsPerPage: number
+}
export async function search({
indexName,
@@ -19,20 +19,20 @@ export async function search({
pageParam,
hitsPerPage = 10,
}: SearchOptions): Promise<{
- hits: Hit[];
- nextPage: number | undefined;
+ hits: Hit[]
+ nextPage: number | undefined
}> {
- const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_SEARCH_API_KEY);
- const index = client.initIndex(indexName);
+ const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_SEARCH_API_KEY)
+ const index = client.initIndex(indexName)
- console.log("alogolia:search", { indexName, query, pageParam, hitsPerPage });
+ console.log('alogolia:search', { indexName, query, pageParam, hitsPerPage })
const { hits, page, nbPages } = await index.search(query, {
page: pageParam,
hitsPerPage,
- });
+ })
- const nextPage = page + 1 < nbPages ? page + 1 : undefined;
+ const nextPage = page + 1 < nbPages ? page + 1 : undefined
- return { hits, nextPage };
+ return { hits, nextPage }
}
diff --git a/examples/react/algolia/src/index.tsx b/examples/react/algolia/src/index.tsx
index 7fabc9c5c9..5580576a6b 100644
--- a/examples/react/algolia/src/index.tsx
+++ b/examples/react/algolia/src/index.tsx
@@ -1,6 +1,6 @@
-import ReactDOM from "react-dom/client";
+import ReactDOM from 'react-dom/client'
-import App from "./App";
+import App from './App'
-const rootElement = document.getElementById("root") as HTMLElement;
-ReactDOM.createRoot(rootElement).render( );
+const rootElement = document.getElementById('root') as HTMLElement
+ReactDOM.createRoot(rootElement).render( )
diff --git a/examples/react/algolia/src/useAlgolia.ts b/examples/react/algolia/src/useAlgolia.ts
index 61f23ffdda..a47b96577d 100644
--- a/examples/react/algolia/src/useAlgolia.ts
+++ b/examples/react/algolia/src/useAlgolia.ts
@@ -1,14 +1,14 @@
-import { useInfiniteQuery } from "@tanstack/react-query";
-import { search } from "./algolia";
+import { useInfiniteQuery } from '@tanstack/react-query'
+import { search } from './algolia'
export type UseAlgoliaOptions = {
- indexName: string;
- query: string;
- hitsPerPage?: number;
- staleTime?: number;
- gcTime?: number;
- enabled?: boolean;
-};
+ indexName: string
+ query: string
+ hitsPerPage?: number
+ staleTime?: number
+ gcTime?: number
+ enabled?: boolean
+}
export default function useAlgolia({
indexName,
@@ -19,7 +19,7 @@ export default function useAlgolia({
enabled,
}: UseAlgoliaOptions) {
const queryInfo = useInfiniteQuery({
- queryKey: ["algolia", indexName, query, hitsPerPage],
+ queryKey: ['algolia', indexName, query, hitsPerPage],
queryFn: ({ pageParam }) =>
search({ indexName, query, pageParam, hitsPerPage }),
defaultPageParam: 0,
@@ -27,9 +27,9 @@ export default function useAlgolia({
staleTime,
gcTime,
enabled,
- });
+ })
- const hits = queryInfo.data?.pages.map((page) => page.hits).flat();
+ const hits = queryInfo.data?.pages.map((page) => page.hits).flat()
- return { ...queryInfo, hits };
+ return { ...queryInfo, hits }
}
diff --git a/examples/react/algolia/vite.config.js b/examples/react/algolia/vite.config.js
index 081c8d9f69..9ffcc67574 100644
--- a/examples/react/algolia/vite.config.js
+++ b/examples/react/algolia/vite.config.js
@@ -1,6 +1,6 @@
-import { defineConfig } from "vite";
-import react from "@vitejs/plugin-react";
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
-});
+})
diff --git a/examples/react/auto-refetching/pages/api/data.js b/examples/react/auto-refetching/src/pages/api/data.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/auto-refetching/pages/api/data.js
rename to examples/react/auto-refetching/src/pages/api/data.js
diff --git a/examples/react/auto-refetching/pages/index.js b/examples/react/auto-refetching/src/pages/index.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/auto-refetching/pages/index.js
rename to examples/react/auto-refetching/src/pages/index.js
diff --git a/examples/react/basic-graphql-request/.prettierrc b/examples/react/basic-graphql-request/.prettierrc
deleted file mode 100644
index 0967ef424b..0000000000
--- a/examples/react/basic-graphql-request/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/examples/react/basic-graphql-request/src/index.jsx b/examples/react/basic-graphql-request/src/index.jsx
index 30a45cfa66..b484d73a23 100644
--- a/examples/react/basic-graphql-request/src/index.jsx
+++ b/examples/react/basic-graphql-request/src/index.jsx
@@ -1,21 +1,21 @@
/* eslint-disable jsx-a11y/anchor-is-valid */
-import React from "react";
-import ReactDOM from "react-dom/client";
+import React from 'react'
+import ReactDOM from 'react-dom/client'
import {
useQuery,
useQueryClient,
QueryClient,
QueryClientProvider,
-} from "@tanstack/react-query";
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
-import { request, gql } from "graphql-request";
+} from '@tanstack/react-query'
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
+import { request, gql } from 'graphql-request'
-const endpoint = "https://graphqlzero.almansi.me/api";
+const endpoint = 'https://graphqlzero.almansi.me/api'
-const queryClient = new QueryClient();
+const queryClient = new QueryClient()
function App() {
- const [postId, setPostId] = React.useState(-1);
+ const [postId, setPostId] = React.useState(-1)
return (
@@ -23,7 +23,7 @@ function App() {
As you visit the posts below, you will notice them in a loading state
the first time you load them. However, after you return to this list and
click on any posts you have already visited again, you will see them
- load instantly and background refresh right before your eyes!{" "}
+ load instantly and background refresh right before your eyes!{' '}
(You may need to throttle your network speed to simulate longer
loading sequences)
@@ -36,12 +36,12 @@ function App() {
)}
- );
+ )
}
function usePosts() {
return useQuery({
- queryKey: ["posts"],
+ queryKey: ['posts'],
queryFn: async () => {
const {
posts: { data },
@@ -56,24 +56,24 @@ function usePosts() {
}
}
}
- `
- );
- return data;
+ `,
+ )
+ return data
},
- });
+ })
}
function Posts({ setPostId }) {
- const queryClient = useQueryClient();
- const { status, data, error, isFetching } = usePosts();
+ const queryClient = useQueryClient()
+ const { status, data, error, isFetching } = usePosts()
return (
Posts
- {status === "pending" ? (
- "Loading..."
- ) : status === "error" ? (
+ {status === 'pending' ? (
+ 'Loading...'
+ ) : status === 'error' ? (
Error: {error.message}
) : (
<>
@@ -86,10 +86,10 @@ function Posts({ setPostId }) {
style={
// We can find the existing query data here to show bold links for
// ones that are cached
- queryClient.getQueryData(["post", post.id])
+ queryClient.getQueryData(['post', post.id])
? {
- fontWeight: "bold",
- color: "green",
+ fontWeight: 'bold',
+ color: 'green',
}
: {}
}
@@ -99,17 +99,17 @@ function Posts({ setPostId }) {
))}
-
{isFetching ? "Background Updating..." : " "}
+
{isFetching ? 'Background Updating...' : ' '}
>
)}
- );
+ )
}
function usePost(postId) {
return useQuery(
- ["post", postId],
+ ['post', postId],
async () => {
const { post } = await request(
endpoint,
@@ -121,19 +121,19 @@ function usePost(postId) {
body
}
}
- `
- );
+ `,
+ )
- return post;
+ return post
},
{
enabled: !!postId,
- }
- );
+ },
+ )
}
function Post({ postId, setPostId }) {
- const { status, data, error, isFetching } = usePost(postId);
+ const { status, data, error, isFetching } = usePost(postId)
return (
@@ -142,9 +142,9 @@ function Post({ postId, setPostId }) {
Back
- {!postId || status === "pending" ? (
- "Loading..."
- ) : status === "error" ? (
+ {!postId || status === 'pending' ? (
+ 'Loading...'
+ ) : status === 'error' ? (
Error: {error.message}
) : (
<>
@@ -152,12 +152,12 @@ function Post({ postId, setPostId }) {
- {isFetching ? "Background Updating..." : " "}
+ {isFetching ? 'Background Updating...' : ' '}
>
)}
- );
+ )
}
-const rootElement = document.getElementById("root");
-ReactDOM.createRoot(rootElement).render( );
+const rootElement = document.getElementById('root')
+ReactDOM.createRoot(rootElement).render( )
diff --git a/examples/react/basic-typescript/.prettierrc b/examples/react/basic-typescript/.prettierrc
deleted file mode 100644
index 0967ef424b..0000000000
--- a/examples/react/basic-typescript/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/examples/react/basic-typescript/src/index.tsx b/examples/react/basic-typescript/src/index.tsx
index 260303483a..34b931bbc4 100644
--- a/examples/react/basic-typescript/src/index.tsx
+++ b/examples/react/basic-typescript/src/index.tsx
@@ -1,11 +1,11 @@
/* eslint-disable jsx-a11y/anchor-is-valid */
-import * as React from "react";
-import ReactDOM from "react-dom/client";
-import axios from "axios";
-import { useQuery, useQueryClient, QueryClient } from "@tanstack/react-query";
-import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
-import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister";
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
+import * as React from 'react'
+import ReactDOM from 'react-dom/client'
+import axios from 'axios'
+import { useQuery, useQueryClient, QueryClient } from '@tanstack/react-query'
+import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
+import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
const queryClient = new QueryClient({
defaultOptions: {
@@ -13,44 +13,44 @@ const queryClient = new QueryClient({
gcTime: 1000 * 60 * 60 * 24, // 24 hours
},
},
-});
+})
const persister = createSyncStoragePersister({
storage: window.localStorage,
-});
+})
type Post = {
- id: number;
- title: string;
- body: string;
-};
+ id: number
+ title: string
+ body: string
+}
function usePosts() {
return useQuery({
- queryKey: ["posts"],
+ queryKey: ['posts'],
queryFn: async (): Promise> => {
const { data } = await axios.get(
- "https://jsonplaceholder.typicode.com/posts"
- );
- return data;
+ 'https://jsonplaceholder.typicode.com/posts',
+ )
+ return data
},
- });
+ })
}
function Posts({
setPostId,
}: {
- setPostId: React.Dispatch>;
+ setPostId: React.Dispatch>
}) {
- const queryClient = useQueryClient();
- const { status, data, error, isFetching } = usePosts();
+ const queryClient = useQueryClient()
+ const { status, data, error, isFetching } = usePosts()
return (
Posts
- {status === "pending" ? (
- "Loading..."
+ {status === 'pending' ? (
+ 'Loading...'
) : error instanceof Error ? (
Error: {error.message}
) : (
@@ -64,10 +64,10 @@ function Posts({
style={
// We can access the query data here to show bold links for
// ones that are cached
- queryClient.getQueryData(["post", post.id])
+ queryClient.getQueryData(['post', post.id])
? {
- fontWeight: "bold",
- color: "green",
+ fontWeight: 'bold',
+ color: 'green',
}
: {}
}
@@ -77,37 +77,37 @@ function Posts({
))}
-
{isFetching ? "Background Updating..." : " "}
+
{isFetching ? 'Background Updating...' : ' '}
>
)}
- );
+ )
}
const getPostById = async (id: number): Promise => {
const { data } = await axios.get(
- `https://jsonplaceholder.typicode.com/posts/${id}`
- );
- return data;
-};
+ `https://jsonplaceholder.typicode.com/posts/${id}`,
+ )
+ return data
+}
function usePost(postId: number) {
return useQuery({
- queryKey: ["post", postId],
+ queryKey: ['post', postId],
queryFn: () => getPostById(postId),
enabled: !!postId,
- });
+ })
}
function Post({
postId,
setPostId,
}: {
- postId: number;
- setPostId: React.Dispatch>;
+ postId: number
+ setPostId: React.Dispatch>
}) {
- const { status, data, error, isFetching } = usePost(postId);
+ const { status, data, error, isFetching } = usePost(postId)
return (
@@ -116,8 +116,8 @@ function Post({
Back
- {!postId || status === "pending" ? (
- "Loading..."
+ {!postId || status === 'pending' ? (
+ 'Loading...'
) : error instanceof Error ? (
Error: {error.message}
) : (
@@ -126,15 +126,15 @@ function Post({
- {isFetching ? "Background Updating..." : " "}
+ {isFetching ? 'Background Updating...' : ' '}
>
)}
- );
+ )
}
function App() {
- const [postId, setPostId] = React.useState(-1);
+ const [postId, setPostId] = React.useState(-1)
return (
(You may need to throttle your network speed to simulate longer
loading sequences)
@@ -158,8 +158,8 @@ function App() {
)}
- );
+ )
}
-const rootElement = document.getElementById("root") as HTMLElement;
-ReactDOM.createRoot(rootElement).render( );
+const rootElement = document.getElementById('root') as HTMLElement
+ReactDOM.createRoot(rootElement).render( )
diff --git a/examples/react/basic-typescript/vite.config.ts b/examples/react/basic-typescript/vite.config.ts
index 9cc50ead1c..5a33944a9b 100644
--- a/examples/react/basic-typescript/vite.config.ts
+++ b/examples/react/basic-typescript/vite.config.ts
@@ -1,7 +1,7 @@
-import { defineConfig } from "vite";
-import react from "@vitejs/plugin-react";
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
-});
+})
diff --git a/examples/react/basic/.prettierrc b/examples/react/basic/.prettierrc
deleted file mode 100644
index 0967ef424b..0000000000
--- a/examples/react/basic/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/examples/react/basic/src/index.jsx b/examples/react/basic/src/index.jsx
index 05590a9512..e038ea9b33 100644
--- a/examples/react/basic/src/index.jsx
+++ b/examples/react/basic/src/index.jsx
@@ -1,19 +1,19 @@
/* eslint-disable jsx-a11y/anchor-is-valid */
-import React from "react";
-import ReactDOM from "react-dom/client";
-import axios from "axios";
+import React from 'react'
+import ReactDOM from 'react-dom/client'
+import axios from 'axios'
import {
useQuery,
useQueryClient,
QueryClient,
QueryClientProvider,
-} from "@tanstack/react-query";
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
+} from '@tanstack/react-query'
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
-const queryClient = new QueryClient();
+const queryClient = new QueryClient()
function App() {
- const [postId, setPostId] = React.useState(-1);
+ const [postId, setPostId] = React.useState(-1)
return (
@@ -21,7 +21,7 @@ function App() {
As you visit the posts below, you will notice them in a loading state
the first time you load them. However, after you return to this list and
click on any posts you have already visited again, you will see them
- load instantly and background refresh right before your eyes!{" "}
+ load instantly and background refresh right before your eyes!{' '}
(You may need to throttle your network speed to simulate longer
loading sequences)
@@ -34,32 +34,32 @@ function App() {
)}
- );
+ )
}
function usePosts() {
return useQuery({
- queryKey: ["posts"],
+ queryKey: ['posts'],
queryFn: async () => {
const { data } = await axios.get(
- "https://jsonplaceholder.typicode.com/posts"
- );
- return data;
+ 'https://jsonplaceholder.typicode.com/posts',
+ )
+ return data
},
- });
+ })
}
function Posts({ setPostId }) {
- const queryClient = useQueryClient();
- const { status, data, error, isFetching } = usePosts();
+ const queryClient = useQueryClient()
+ const { status, data, error, isFetching } = usePosts()
return (
Posts
- {status === "pending" ? (
- "Loading..."
- ) : status === "error" ? (
+ {status === 'pending' ? (
+ 'Loading...'
+ ) : status === 'error' ? (
Error: {error.message}
) : (
<>
@@ -72,10 +72,10 @@ function Posts({ setPostId }) {
style={
// We can access the query data here to show bold links for
// ones that are cached
- queryClient.getQueryData(["post", post.id])
+ queryClient.getQueryData(['post', post.id])
? {
- fontWeight: "bold",
- color: "green",
+ fontWeight: 'bold',
+ color: 'green',
}
: {}
}
@@ -85,31 +85,31 @@ function Posts({ setPostId }) {
))}
-
{isFetching ? "Background Updating..." : " "}
+
{isFetching ? 'Background Updating...' : ' '}
>
)}
- );
+ )
}
const getPostById = async (id) => {
const { data } = await axios.get(
- `https://jsonplaceholder.typicode.com/posts/${id}`
- );
- return data;
-};
+ `https://jsonplaceholder.typicode.com/posts/${id}`,
+ )
+ return data
+}
function usePost(postId) {
return useQuery({
- queryKey: ["post", postId],
+ queryKey: ['post', postId],
queryFn: () => getPostById(postId),
enabled: !!postId,
- });
+ })
}
function Post({ postId, setPostId }) {
- const { status, data, error, isFetching } = usePost(postId);
+ const { status, data, error, isFetching } = usePost(postId)
return (
@@ -118,9 +118,9 @@ function Post({ postId, setPostId }) {
Back
- {!postId || status === "pending" ? (
- "Loading..."
- ) : status === "error" ? (
+ {!postId || status === 'pending' ? (
+ 'Loading...'
+ ) : status === 'error' ? (
Error: {error.message}
) : (
<>
@@ -128,12 +128,12 @@ function Post({ postId, setPostId }) {
- {isFetching ? "Background Updating..." : " "}
+ {isFetching ? 'Background Updating...' : ' '}
>
)}
- );
+ )
}
-const rootElement = document.getElementById("root");
-ReactDOM.createRoot(rootElement).render( );
+const rootElement = document.getElementById('root')
+ReactDOM.createRoot(rootElement).render( )
diff --git a/examples/react/default-query-function/.prettierrc b/examples/react/default-query-function/.prettierrc
deleted file mode 100644
index 0967ef424b..0000000000
--- a/examples/react/default-query-function/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/examples/react/default-query-function/package.json b/examples/react/default-query-function/package.json
index dafb1d1e79..d21a3a06ee 100644
--- a/examples/react/default-query-function/package.json
+++ b/examples/react/default-query-function/package.json
@@ -8,11 +8,11 @@
"preview": "vite preview"
},
"dependencies": {
+ "@tanstack/react-query": "^5.0.0-alpha.38",
+ "@tanstack/react-query-devtools": "^5.0.0-alpha.38",
"axios": "^1.4.0",
"react": "^18.2.0",
- "react-dom": "^18.2.0",
- "@tanstack/react-query": "^5.0.0-alpha.38",
- "@tanstack/react-query-devtools": "^5.0.0-alpha.38"
+ "react-dom": "^18.2.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.0.0",
diff --git a/examples/react/default-query-function/src/index.jsx b/examples/react/default-query-function/src/index.jsx
index 88fba6e3d7..5b494df68e 100644
--- a/examples/react/default-query-function/src/index.jsx
+++ b/examples/react/default-query-function/src/index.jsx
@@ -1,22 +1,22 @@
/* eslint-disable jsx-a11y/anchor-is-valid */
-import React from "react";
-import ReactDOM from "react-dom/client";
-import axios from "axios";
+import React from 'react'
+import ReactDOM from 'react-dom/client'
+import axios from 'axios'
import {
useQuery,
useQueryClient,
QueryClient,
QueryClientProvider,
-} from "@tanstack/react-query";
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
+} from '@tanstack/react-query'
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
// Define a default query function that will receive the query key
const defaultQueryFn = async ({ queryKey }) => {
const { data } = await axios.get(
- `https://jsonplaceholder.typicode.com${queryKey[0]}`
- );
- return data;
-};
+ `https://jsonplaceholder.typicode.com${queryKey[0]}`,
+ )
+ return data
+}
// provide the default query function to your app via the query client
const queryClient = new QueryClient({
@@ -25,10 +25,10 @@ const queryClient = new QueryClient({
queryFn: defaultQueryFn,
},
},
-});
+})
function App() {
- const [postId, setPostId] = React.useState(-1);
+ const [postId, setPostId] = React.useState(-1)
return (
@@ -36,7 +36,7 @@ function App() {
As you visit the posts below, you will notice them in a loading state
the first time you load them. However, after you return to this list and
click on any posts you have already visited again, you will see them
- load instantly and background refresh right before your eyes!{" "}
+ load instantly and background refresh right before your eyes!{' '}
(You may need to throttle your network speed to simulate longer
loading sequences)
@@ -49,24 +49,24 @@ function App() {
)}
- );
+ )
}
function Posts({ setPostId }) {
- const queryClient = useQueryClient();
+ const queryClient = useQueryClient()
// All you have to do now is pass a key!
const { status, data, error, isFetching } = useQuery({
- queryKey: ["/posts"],
- });
+ queryKey: ['/posts'],
+ })
return (
Posts
- {status === "pending" ? (
- "Loading..."
- ) : status === "error" ? (
+ {status === 'pending' ? (
+ 'Loading...'
+ ) : status === 'error' ? (
Error: {error.message}
) : (
<>
@@ -79,10 +79,10 @@ function Posts({ setPostId }) {
style={
// We can use the queryCache here to show bold links for
// ones that are cached
- queryClient.getQueryData(["post", post.id])
+ queryClient.getQueryData(['post', post.id])
? {
- fontWeight: "bold",
- color: "green",
+ fontWeight: 'bold',
+ color: 'green',
}
: {}
}
@@ -92,12 +92,12 @@ function Posts({ setPostId }) {
))}
-
{isFetching ? "Background Updating..." : " "}
+
{isFetching ? 'Background Updating...' : ' '}
>
)}
- );
+ )
}
function Post({ postId, setPostId }) {
@@ -105,7 +105,7 @@ function Post({ postId, setPostId }) {
const { status, data, error, isFetching } = useQuery({
queryKey: [`/posts/${postId}`],
enabled: !!postId,
- });
+ })
return (
@@ -114,9 +114,9 @@ function Post({ postId, setPostId }) {
Back
- {!postId || status === "pending" ? (
- "Loading..."
- ) : status === "error" ? (
+ {!postId || status === 'pending' ? (
+ 'Loading...'
+ ) : status === 'error' ? (
Error: {error.message}
) : (
<>
@@ -124,12 +124,12 @@ function Post({ postId, setPostId }) {
- {isFetching ? "Background Updating..." : " "}
+ {isFetching ? 'Background Updating...' : ' '}
>
)}
- );
+ )
}
-const rootElement = document.getElementById("root");
-ReactDOM.createRoot(rootElement).render( );
+const rootElement = document.getElementById('root')
+ReactDOM.createRoot(rootElement).render( )
diff --git a/examples/react/infinite-query-with-max-pages/pages/api/projects.js b/examples/react/infinite-query-with-max-pages/src/pages/api/projects.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/infinite-query-with-max-pages/pages/api/projects.js
rename to examples/react/infinite-query-with-max-pages/src/pages/api/projects.js
diff --git a/examples/react/infinite-query-with-max-pages/pages/index.js b/examples/react/infinite-query-with-max-pages/src/pages/index.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/infinite-query-with-max-pages/pages/index.js
rename to examples/react/infinite-query-with-max-pages/src/pages/index.js
diff --git a/examples/react/load-more-infinite-scroll/pages/about.js b/examples/react/load-more-infinite-scroll/src/pages/about.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/load-more-infinite-scroll/pages/about.js
rename to examples/react/load-more-infinite-scroll/src/pages/about.js
diff --git a/examples/react/load-more-infinite-scroll/pages/api/projects.js b/examples/react/load-more-infinite-scroll/src/pages/api/projects.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/load-more-infinite-scroll/pages/api/projects.js
rename to examples/react/load-more-infinite-scroll/src/pages/api/projects.js
diff --git a/examples/react/load-more-infinite-scroll/pages/index.js b/examples/react/load-more-infinite-scroll/src/pages/index.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/load-more-infinite-scroll/pages/index.js
rename to examples/react/load-more-infinite-scroll/src/pages/index.js
diff --git a/examples/react/nextjs/package.json b/examples/react/nextjs/package.json
index 6e6e111b24..dc2da5f154 100644
--- a/examples/react/nextjs/package.json
+++ b/examples/react/nextjs/package.json
@@ -1,22 +1,21 @@
{
"name": "@tanstack/query-example-react-nextjs",
"version": "1.0.0",
+ "license": "MIT",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
+ "@tanstack/react-query": "^5.0.0-alpha.38",
+ "@tanstack/react-query-devtools": "^5.0.0-alpha.38",
"ky": "^0.33.3",
"ky-universal": "^0.11.0",
"next": "^13.4.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
- "@tanstack/react-query": "^5.0.0-alpha.38",
- "@tanstack/react-query-devtools": "^5.0.0-alpha.38",
"resolve-from": "^5.0.0",
"web-streams-polyfill": "^3.0.3"
- },
- "license": "MIT",
- "devDependencies": {}
+ }
}
diff --git a/examples/react/nextjs/components/Header/index.js b/examples/react/nextjs/src/components/Header/index.js
similarity index 100%
rename from examples/react/nextjs/components/Header/index.js
rename to examples/react/nextjs/src/components/Header/index.js
diff --git a/examples/react/nextjs/components/InfoBox/index.js b/examples/react/nextjs/src/components/InfoBox/index.js
similarity index 100%
rename from examples/react/nextjs/components/InfoBox/index.js
rename to examples/react/nextjs/src/components/InfoBox/index.js
diff --git a/examples/react/nextjs/components/Layout/index.js b/examples/react/nextjs/src/components/Layout/index.js
similarity index 100%
rename from examples/react/nextjs/components/Layout/index.js
rename to examples/react/nextjs/src/components/Layout/index.js
diff --git a/examples/react/nextjs/components/PostList/index.js b/examples/react/nextjs/src/components/PostList/index.js
similarity index 100%
rename from examples/react/nextjs/components/PostList/index.js
rename to examples/react/nextjs/src/components/PostList/index.js
diff --git a/examples/react/nextjs/components/index.js b/examples/react/nextjs/src/components/index.js
similarity index 100%
rename from examples/react/nextjs/components/index.js
rename to examples/react/nextjs/src/components/index.js
diff --git a/examples/react/nextjs/hooks/index.js b/examples/react/nextjs/src/hooks/index.js
similarity index 100%
rename from examples/react/nextjs/hooks/index.js
rename to examples/react/nextjs/src/hooks/index.js
diff --git a/examples/react/nextjs/hooks/usePosts/index.js b/examples/react/nextjs/src/hooks/usePosts/index.js
similarity index 100%
rename from examples/react/nextjs/hooks/usePosts/index.js
rename to examples/react/nextjs/src/hooks/usePosts/index.js
diff --git a/examples/react/nextjs/pages/_app.js b/examples/react/nextjs/src/pages/_app.js
similarity index 100%
rename from examples/react/nextjs/pages/_app.js
rename to examples/react/nextjs/src/pages/_app.js
diff --git a/examples/react/nextjs/pages/client-only.js b/examples/react/nextjs/src/pages/client-only.js
similarity index 100%
rename from examples/react/nextjs/pages/client-only.js
rename to examples/react/nextjs/src/pages/client-only.js
diff --git a/examples/react/nextjs/pages/index.js b/examples/react/nextjs/src/pages/index.js
similarity index 100%
rename from examples/react/nextjs/pages/index.js
rename to examples/react/nextjs/src/pages/index.js
diff --git a/examples/react/offline/.prettierrc b/examples/react/offline/.prettierrc
deleted file mode 100644
index 0967ef424b..0000000000
--- a/examples/react/offline/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/examples/react/offline/package.json b/examples/react/offline/package.json
index 654c91e247..0dcd59f4ab 100644
--- a/examples/react/offline/package.json
+++ b/examples/react/offline/package.json
@@ -9,15 +9,15 @@
},
"dependencies": {
"@tanstack/react-location": "^3.7.0",
+ "@tanstack/react-query": "^5.0.0-alpha.38",
+ "@tanstack/react-query-devtools": "^5.0.0-alpha.38",
+ "@tanstack/react-query-persist-client": "^5.0.0-alpha.38",
+ "@tanstack/query-sync-storage-persister": "^5.0.0-alpha.38",
"ky": "^0.33.3",
"msw": "^0.39.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
- "react-hot-toast": "^2.4.1",
- "@tanstack/react-query": "^5.0.0-alpha.38",
- "@tanstack/react-query-devtools": "^5.0.0-alpha.38",
- "@tanstack/react-query-persist-client": "^5.0.0-alpha.38",
- "@tanstack/query-sync-storage-persister": "^5.0.0-alpha.38"
+ "react-hot-toast": "^2.4.1"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.0.0",
diff --git a/examples/react/offline/public/mockServiceWorker.js b/examples/react/offline/public/mockServiceWorker.js
index ae4e96565b..ba0c013b83 100644
--- a/examples/react/offline/public/mockServiceWorker.js
+++ b/examples/react/offline/public/mockServiceWorker.js
@@ -8,118 +8,118 @@
* - Please do NOT serve this file on production.
*/
-const INTEGRITY_CHECKSUM = "02f4ad4a2797f85668baf196e553d929";
-const bypassHeaderName = "x-msw-bypass";
-const activeClientIds = new Set();
+const INTEGRITY_CHECKSUM = '02f4ad4a2797f85668baf196e553d929'
+const bypassHeaderName = 'x-msw-bypass'
+const activeClientIds = new Set()
-self.addEventListener("install", function () {
- return self.skipWaiting();
-});
+self.addEventListener('install', function () {
+ return self.skipWaiting()
+})
-self.addEventListener("activate", async function (event) {
- return self.clients.claim();
-});
+self.addEventListener('activate', async function (event) {
+ return self.clients.claim()
+})
-self.addEventListener("message", async function (event) {
- const clientId = event.source.id;
+self.addEventListener('message', async function (event) {
+ const clientId = event.source.id
if (!clientId || !self.clients) {
- return;
+ return
}
- const client = await self.clients.get(clientId);
+ const client = await self.clients.get(clientId)
if (!client) {
- return;
+ return
}
- const allClients = await self.clients.matchAll();
+ const allClients = await self.clients.matchAll()
switch (event.data) {
- case "KEEPALIVE_REQUEST": {
+ case 'KEEPALIVE_REQUEST': {
sendToClient(client, {
- type: "KEEPALIVE_RESPONSE",
- });
- break;
+ type: 'KEEPALIVE_RESPONSE',
+ })
+ break
}
- case "INTEGRITY_CHECK_REQUEST": {
+ case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
- type: "INTEGRITY_CHECK_RESPONSE",
+ type: 'INTEGRITY_CHECK_RESPONSE',
payload: INTEGRITY_CHECKSUM,
- });
- break;
+ })
+ break
}
- case "MOCK_ACTIVATE": {
- activeClientIds.add(clientId);
+ case 'MOCK_ACTIVATE': {
+ activeClientIds.add(clientId)
sendToClient(client, {
- type: "MOCKING_ENABLED",
+ type: 'MOCKING_ENABLED',
payload: true,
- });
- break;
+ })
+ break
}
- case "MOCK_DEACTIVATE": {
- activeClientIds.delete(clientId);
- break;
+ case 'MOCK_DEACTIVATE': {
+ activeClientIds.delete(clientId)
+ break
}
- case "CLIENT_CLOSED": {
- activeClientIds.delete(clientId);
+ case 'CLIENT_CLOSED': {
+ activeClientIds.delete(clientId)
const remainingClients = allClients.filter((client) => {
- return client.id !== clientId;
- });
+ return client.id !== clientId
+ })
// Unregister itself when there are no more clients
if (remainingClients.length === 0) {
- self.registration.unregister();
+ self.registration.unregister()
}
- break;
+ break
}
}
-});
+})
// Resolve the "main" client for the given event.
// Client that issues a request doesn't necessarily equal the client
// that registered the worker. It's with the latter the worker should
// communicate with during the response resolving phase.
async function resolveMainClient(event) {
- const client = await self.clients.get(event.clientId);
+ const client = await self.clients.get(event.clientId)
- if (client.frameType === "top-level") {
- return client;
+ if (client.frameType === 'top-level') {
+ return client
}
- const allClients = await self.clients.matchAll();
+ const allClients = await self.clients.matchAll()
return allClients
.filter((client) => {
// Get only those clients that are currently visible.
- return client.visibilityState === "visible";
+ return client.visibilityState === 'visible'
})
.find((client) => {
// Find the client ID that's recorded in the
// set of clients that have registered the worker.
- return activeClientIds.has(client.id);
- });
+ return activeClientIds.has(client.id)
+ })
}
async function handleRequest(event, requestId) {
- const client = await resolveMainClient(event);
- const response = await getResponse(event, client, requestId);
+ const client = await resolveMainClient(event)
+ const response = await getResponse(event, client, requestId)
// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
- (async function () {
- const clonedResponse = response.clone();
+ ;(async function () {
+ const clonedResponse = response.clone()
sendToClient(client, {
- type: "RESPONSE",
+ type: 'RESPONSE',
payload: {
requestId,
type: clonedResponse.type,
@@ -131,21 +131,21 @@ async function handleRequest(event, requestId) {
headers: serializeHeaders(clonedResponse.headers),
redirected: clonedResponse.redirected,
},
- });
- })();
+ })
+ })()
}
- return response;
+ return response
}
async function getResponse(event, client, requestId) {
- const { request } = event;
- const requestClone = request.clone();
- const getOriginalResponse = () => fetch(requestClone);
+ const { request } = event
+ const requestClone = request.clone()
+ const getOriginalResponse = () => fetch(requestClone)
// Bypass mocking when the request client is not active.
if (!client) {
- return getOriginalResponse();
+ return getOriginalResponse()
}
// Bypass initial page load requests (i.e. static assets).
@@ -153,29 +153,29 @@ async function getResponse(event, client, requestId) {
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
// and is not ready to handle requests.
if (!activeClientIds.has(client.id)) {
- return await getOriginalResponse();
+ return await getOriginalResponse()
}
// Bypass requests with the explicit bypass header
- if (requestClone.headers.get(bypassHeaderName) === "true") {
- const cleanRequestHeaders = serializeHeaders(requestClone.headers);
+ if (requestClone.headers.get(bypassHeaderName) === 'true') {
+ const cleanRequestHeaders = serializeHeaders(requestClone.headers)
// Remove the bypass header to comply with the CORS preflight check.
- delete cleanRequestHeaders[bypassHeaderName];
+ delete cleanRequestHeaders[bypassHeaderName]
const originalRequest = new Request(requestClone, {
headers: new Headers(cleanRequestHeaders),
- });
+ })
- return fetch(originalRequest);
+ return fetch(originalRequest)
}
// Send the request to the client-side MSW.
- const reqHeaders = serializeHeaders(request.headers);
- const body = await request.text();
+ const reqHeaders = serializeHeaders(request.headers)
+ const body = await request.text()
const clientMessage = await sendToClient(client, {
- type: "REQUEST",
+ type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
@@ -193,31 +193,31 @@ async function getResponse(event, client, requestId) {
bodyUsed: request.bodyUsed,
keepalive: request.keepalive,
},
- });
+ })
switch (clientMessage.type) {
- case "MOCK_SUCCESS": {
+ case 'MOCK_SUCCESS': {
return delayPromise(
() => respondWithMock(clientMessage),
- clientMessage.payload.delay
- );
+ clientMessage.payload.delay,
+ )
}
- case "MOCK_NOT_FOUND": {
- return getOriginalResponse();
+ case 'MOCK_NOT_FOUND': {
+ return getOriginalResponse()
}
- case "NETWORK_ERROR": {
- const { name, message } = clientMessage.payload;
- const networkError = new Error(message);
- networkError.name = name;
+ case 'NETWORK_ERROR': {
+ const { name, message } = clientMessage.payload
+ const networkError = new Error(message)
+ networkError.name = name
// Rejecting a request Promise emulates a network error.
- throw networkError;
+ throw networkError
}
- case "INTERNAL_ERROR": {
- const parsedBody = JSON.parse(clientMessage.payload.body);
+ case 'INTERNAL_ERROR': {
+ const parsedBody = JSON.parse(clientMessage.payload.body)
console.error(
`\
@@ -228,54 +228,54 @@ ${parsedBody.location}
This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses\
`,
request.method,
- request.url
- );
+ request.url,
+ )
- return respondWithMock(clientMessage);
+ return respondWithMock(clientMessage)
}
}
- return getOriginalResponse();
+ return getOriginalResponse()
}
-self.addEventListener("fetch", function (event) {
- const { request } = event;
- const accept = request.headers.get("accept") || "";
+self.addEventListener('fetch', function (event) {
+ const { request } = event
+ const accept = request.headers.get('accept') || ''
// Bypass server-sent events.
- if (accept.includes("text/event-stream")) {
- return;
+ if (accept.includes('text/event-stream')) {
+ return
}
// Bypass navigation requests.
- if (request.mode === "navigate") {
- return;
+ if (request.mode === 'navigate') {
+ return
}
// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
- if (request.cache === "only-if-cached" && request.mode !== "same-origin") {
- return;
+ if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
+ return
}
// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
// after it's been deleted (still remains active until the next reload).
if (activeClientIds.size === 0) {
- return;
+ return
}
- const requestId = uuidv4();
+ const requestId = uuidv4()
return event.respondWith(
handleRequest(event, requestId).catch((error) => {
- if (error.name === "NetworkError") {
+ if (error.name === 'NetworkError') {
console.warn(
'[MSW] Successfully emulated a network error for the "%s %s" request.',
request.method,
- request.url
- );
- return;
+ request.url,
+ )
+ return
}
// At this point, any exception indicates an issue with the original request/response.
@@ -284,55 +284,55 @@ self.addEventListener("fetch", function (event) {
[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
request.method,
request.url,
- `${error.name}: ${error.message}`
- );
- })
- );
-});
+ `${error.name}: ${error.message}`,
+ )
+ }),
+ )
+})
function serializeHeaders(headers) {
- const reqHeaders = {};
+ const reqHeaders = {}
headers.forEach((value, name) => {
reqHeaders[name] = reqHeaders[name]
? [].concat(reqHeaders[name]).concat(value)
- : value;
- });
- return reqHeaders;
+ : value
+ })
+ return reqHeaders
}
function sendToClient(client, message) {
return new Promise((resolve, reject) => {
- const channel = new MessageChannel();
+ const channel = new MessageChannel()
channel.port1.onmessage = (event) => {
if (event.data && event.data.error) {
- return reject(event.data.error);
+ return reject(event.data.error)
}
- resolve(event.data);
- };
+ resolve(event.data)
+ }
- client.postMessage(JSON.stringify(message), [channel.port2]);
- });
+ client.postMessage(JSON.stringify(message), [channel.port2])
+ })
}
function delayPromise(cb, duration) {
return new Promise((resolve) => {
- setTimeout(() => resolve(cb()), duration);
- });
+ setTimeout(() => resolve(cb()), duration)
+ })
}
function respondWithMock(clientMessage) {
return new Response(clientMessage.payload.body, {
...clientMessage.payload,
headers: clientMessage.payload.headers,
- });
+ })
}
function uuidv4() {
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
- const r = (Math.random() * 16) | 0;
- const v = c == "x" ? r : (r & 0x3) | 0x8;
- return v.toString(16);
- });
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
+ const r = (Math.random() * 16) | 0
+ const v = c == 'x' ? r : (r & 0x3) | 0x8
+ return v.toString(16)
+ })
}
diff --git a/examples/react/offline/src/App.jsx b/examples/react/offline/src/App.jsx
index 3cd0aa9178..5e430e8187 100644
--- a/examples/react/offline/src/App.jsx
+++ b/examples/react/offline/src/App.jsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import * as React from 'react'
import {
useQuery,
@@ -6,28 +6,28 @@ import {
MutationCache,
onlineManager,
useIsRestoring,
-} from "@tanstack/react-query";
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
-import toast, { Toaster } from "react-hot-toast";
+} from '@tanstack/react-query'
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
+import toast, { Toaster } from 'react-hot-toast'
-import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
-import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister";
+import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
+import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
import {
Link,
Outlet,
ReactLocation,
Router,
useMatch,
-} from "@tanstack/react-location";
+} from '@tanstack/react-location'
-import * as api from "./api";
-import { movieKeys, useMovie } from "./movies";
+import * as api from './api'
+import { movieKeys, useMovie } from './movies'
const persister = createSyncStoragePersister({
storage: window.localStorage,
-});
+})
-const location = new ReactLocation();
+const location = new ReactLocation()
const queryClient = new QueryClient({
defaultOptions: {
@@ -40,22 +40,22 @@ const queryClient = new QueryClient({
// configure global cache callbacks to show toast notifications
mutationCache: new MutationCache({
onSuccess: (data) => {
- toast.success(data.message);
+ toast.success(data.message)
},
onError: (error) => {
- toast.error(error.message);
+ toast.error(error.message)
},
}),
-});
+})
// we need a default mutation function so that paused mutations can resume after a page reload
queryClient.setMutationDefaults(movieKeys.all(), {
mutationFn: async ({ id, comment }) => {
// to avoid clashes with our optimistic update when an offline mutation continues
- await queryClient.cancelQueries({ queryKey: movieKeys.detail(id) });
- return api.updateMovie(id, comment);
+ await queryClient.cancelQueries({ queryKey: movieKeys.detail(id) })
+ return api.updateMovie(id, comment)
},
-});
+})
export default function App() {
return (
@@ -65,28 +65,28 @@ export default function App() {
onSuccess={() => {
// resume mutations after initial restore from localStorage was successful
queryClient.resumePausedMutations().then(() => {
- queryClient.invalidateQueries();
- });
+ queryClient.invalidateQueries()
+ })
}}
>
- );
+ )
}
function Movies() {
- const isRestoring = useIsRestoring();
+ const isRestoring = useIsRestoring()
return (
,
},
{
- path: ":movieId",
+ path: ':movieId',
element: ,
errorElement: ,
loader: ({ params: { movieId } }) =>
@@ -105,17 +105,17 @@ function Movies() {
- );
+ )
}
function List() {
const moviesQuery = useQuery({
queryKey: movieKeys.list(),
queryFn: api.fetchMovies,
- });
+ })
if (moviesQuery.isLoading) {
- return "Loading...";
+ return 'Loading...'
}
if (moviesQuery.data) {
@@ -139,17 +139,17 @@ function List() {
Updated at: {new Date(moviesQuery.data.ts).toLocaleTimeString()}
- {moviesQuery.isFetching && "fetching..."}
+ {moviesQuery.isFetching && 'fetching...'}
- );
+ )
}
// query will be in 'idle' fetchStatus while restoring from localStorage
- return null;
+ return null
}
function MovieError() {
- const { error } = useMatch();
+ const { error } = useMatch()
return (
@@ -157,26 +157,26 @@ function MovieError() {
Couldn't load movie!
{error.message}
- );
+ )
}
function Detail() {
const {
params: { movieId },
- } = useMatch();
- const { comment, setComment, updateMovie, movieQuery } = useMovie(movieId);
+ } = useMatch()
+ const { comment, setComment, updateMovie, movieQuery } = useMovie(movieId)
if (movieQuery.isLoading) {
- return "Loading...";
+ return 'Loading...'
}
function submitForm(event) {
- event.preventDefault();
+ event.preventDefault()
updateMovie.mutate({
id: movieId,
comment,
- });
+ })
}
if (movieQuery.data) {
@@ -207,19 +207,19 @@ function Detail() {
Updated at: {new Date(movieQuery.data.ts).toLocaleTimeString()}
- {movieQuery.isFetching && "fetching..."}
+ {movieQuery.isFetching && 'fetching...'}
{updateMovie.isPaused
- ? "mutation paused - offline"
- : updateMovie.isPending && "updating..."}
+ ? 'mutation paused - offline'
+ : updateMovie.isPending && 'updating...'}
- );
+ )
}
if (movieQuery.isPaused) {
- return "We're offline and have no data to show :(";
+ return "We're offline and have no data to show :("
}
- return null;
+ return null
}
diff --git a/examples/react/offline/src/api.js b/examples/react/offline/src/api.js
index 1bb7d0a9e0..582d56dbf3 100644
--- a/examples/react/offline/src/api.js
+++ b/examples/react/offline/src/api.js
@@ -1,41 +1,41 @@
-import { setupWorker, rest } from "msw";
-import ky from "ky";
+import { setupWorker, rest } from 'msw'
+import ky from 'ky'
const movies = [
{
- id: "1",
- title: "Guardians of the Galaxy",
- comment: "",
+ id: '1',
+ title: 'Guardians of the Galaxy',
+ comment: '',
},
{
- id: "2",
- title: "Wall-E",
- comment: "",
+ id: '2',
+ title: 'Wall-E',
+ comment: '',
},
-];
+]
-export const fetchMovie = (id) => ky.get(`/movies/${id}`).json();
-export const fetchMovies = () => ky.get("/movies").json();
+export const fetchMovie = (id) => ky.get(`/movies/${id}`).json()
+export const fetchMovies = () => ky.get('/movies').json()
export const updateMovie = (id, comment) =>
- ky.post(`/movies/${id}`, { json: { comment } }).json();
+ ky.post(`/movies/${id}`, { json: { comment } }).json()
export const worker = setupWorker(
...[
- rest.get("/movies", (req, res, ctx) => {
+ rest.get('/movies', (req, res, ctx) => {
return res(
ctx.delay(1000),
ctx.json({
ts: Date.now(),
movies: movies.map(({ id, title }) => ({ id, title })),
- })
- );
+ }),
+ )
}),
- rest.get("/movies/:id", (req, res, ctx) => {
- const { id } = req.params;
+ rest.get('/movies/:id', (req, res, ctx) => {
+ const { id } = req.params
- const movie = movies.find((movie) => movie.id === id);
+ const movie = movies.find((movie) => movie.id === id)
if (!movie) {
- return res(ctx.status(404, `Movie with id ${id} not found`));
+ return res(ctx.status(404, `Movie with id ${id} not found`))
}
return res(
@@ -43,25 +43,25 @@ export const worker = setupWorker(
ctx.json({
ts: Date.now(),
movie,
- })
- );
+ }),
+ )
}),
- rest.post("/movies/:id", (req, res, ctx) => {
- const { id } = req.params;
- const { comment } = req.body;
+ rest.post('/movies/:id', (req, res, ctx) => {
+ const { id } = req.params
+ const { comment } = req.body
movies.forEach((movie) => {
if (movie.id === id) {
- movie.comment = comment.toUpperCase();
+ movie.comment = comment.toUpperCase()
}
- });
+ })
return res(
ctx.delay(1000),
ctx.json({
message: `Successfully updated movie ${id}`,
- })
- );
+ }),
+ )
}),
- ]
-);
+ ],
+)
diff --git a/examples/react/offline/src/index.jsx b/examples/react/offline/src/index.jsx
index 98b53092e8..026a35b323 100644
--- a/examples/react/offline/src/index.jsx
+++ b/examples/react/offline/src/index.jsx
@@ -1,13 +1,13 @@
-import React from "react";
-import ReactDOM from "react-dom/client";
-import App from "./App";
-import { worker } from "./api";
+import React from 'react'
+import ReactDOM from 'react-dom/client'
+import App from './App'
+import { worker } from './api'
-worker.start();
+worker.start()
-const rootElement = document.getElementById("root");
+const rootElement = document.getElementById('root')
ReactDOM.createRoot(rootElement).render(
- ,
+)
diff --git a/examples/react/offline/src/movies.js b/examples/react/offline/src/movies.js
index 67999c5ec9..12fb656539 100644
--- a/examples/react/offline/src/movies.js
+++ b/examples/react/offline/src/movies.js
@@ -1,32 +1,32 @@
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import * as api from "./api";
-import * as React from "react";
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import * as api from './api'
+import * as React from 'react'
export const movieKeys = {
- all: () => ["movies"],
- list: () => [...movieKeys.all(), "list"],
- details: () => [...movieKeys.all(), "detail"],
+ all: () => ['movies'],
+ list: () => [...movieKeys.all(), 'list'],
+ details: () => [...movieKeys.all(), 'detail'],
detail: (id) => [...movieKeys.details(), id],
-};
+}
export const useMovie = (movieId) => {
- const queryClient = useQueryClient();
+ const queryClient = useQueryClient()
const movieQuery = useQuery({
queryKey: movieKeys.detail(movieId),
queryFn: () => api.fetchMovie(movieId),
- });
+ })
- const [comment, setComment] = React.useState();
+ const [comment, setComment] = React.useState()
const updateMovie = useMutation({
mutationKey: movieKeys.detail(movieId),
onMutate: async () => {
- await queryClient.cancelQueries({ queryKey: movieKeys.detail(movieId) });
- const previousData = queryClient.getQueryData(movieKeys.detail(movieId));
+ await queryClient.cancelQueries({ queryKey: movieKeys.detail(movieId) })
+ const previousData = queryClient.getQueryData(movieKeys.detail(movieId))
// remove local state so that server state is taken instead
- setComment(undefined);
+ setComment(undefined)
queryClient.setQueryData(movieKeys.detail(movieId), {
...previousData,
@@ -34,22 +34,22 @@ export const useMovie = (movieId) => {
...previousData.movie,
comment,
},
- });
+ })
- return { previousData };
+ return { previousData }
},
onError: (_, __, context) => {
- queryClient.setQueryData(movieKeys.detail(movieId), context.previousData);
+ queryClient.setQueryData(movieKeys.detail(movieId), context.previousData)
},
onSettled: () => {
- queryClient.invalidateQueries({ queryKey: movieKeys.detail(movieId) });
+ queryClient.invalidateQueries({ queryKey: movieKeys.detail(movieId) })
},
- });
+ })
return {
comment: comment ?? movieQuery.data?.movie.comment,
setComment,
updateMovie,
movieQuery,
- };
-};
+ }
+}
diff --git a/examples/react/optimistic-updates-typescript/pages/api/data.js b/examples/react/optimistic-updates-typescript/src/pages/api/data.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/optimistic-updates-typescript/pages/api/data.js
rename to examples/react/optimistic-updates-typescript/src/pages/api/data.js
diff --git a/examples/react/optimistic-updates-typescript/pages/index.tsx b/examples/react/optimistic-updates-typescript/src/pages/index.tsx
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/optimistic-updates-typescript/pages/index.tsx
rename to examples/react/optimistic-updates-typescript/src/pages/index.tsx
diff --git a/examples/react/optimistic-updates-typescript/tsconfig.json b/examples/react/optimistic-updates-typescript/tsconfig.json
index aebbceec22..d04e1b9de1 100644
--- a/examples/react/optimistic-updates-typescript/tsconfig.json
+++ b/examples/react/optimistic-updates-typescript/tsconfig.json
@@ -1,5 +1,4 @@
{
- "include": ["./pages/**/*"],
"compilerOptions": {
"strict": true,
"esModuleInterop": true,
@@ -16,5 +15,6 @@
"isolatedModules": true,
"incremental": true
},
+ "include": ["src"],
"exclude": ["node_modules"]
}
diff --git a/examples/react/pagination/pages/api/projects.js b/examples/react/pagination/src/pages/api/projects.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/pagination/pages/api/projects.js
rename to examples/react/pagination/src/pages/api/projects.js
diff --git a/examples/react/pagination/pages/index.js b/examples/react/pagination/src/pages/index.js
similarity index 100%
rename from examples/react/pagination/pages/index.js
rename to examples/react/pagination/src/pages/index.js
diff --git a/examples/react/playground/.prettierrc b/examples/react/playground/.prettierrc
deleted file mode 100644
index 9e26dfeeb6..0000000000
--- a/examples/react/playground/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
\ No newline at end of file
diff --git a/examples/react/playground/package.json b/examples/react/playground/package.json
index 628a95dbb5..f7aeb72533 100644
--- a/examples/react/playground/package.json
+++ b/examples/react/playground/package.json
@@ -8,10 +8,10 @@
"preview": "vite preview"
},
"dependencies": {
- "react": "^18.2.0",
- "react-dom": "^18.2.0",
"@tanstack/react-query": "^5.0.0-alpha.38",
- "@tanstack/react-query-devtools": "^5.0.0-alpha.38"
+ "@tanstack/react-query-devtools": "^5.0.0-alpha.38",
+ "react": "^18.2.0",
+ "react-dom": "^18.2.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.0.0",
diff --git a/examples/react/playground/src/index.jsx b/examples/react/playground/src/index.jsx
index 1bb801f72d..be22c2140f 100644
--- a/examples/react/playground/src/index.jsx
+++ b/examples/react/playground/src/index.jsx
@@ -1,5 +1,5 @@
-import React from "react";
-import ReactDOM from "react-dom/client";
+import React from 'react'
+import ReactDOM from 'react-dom/client'
import {
QueryClient,
@@ -7,42 +7,40 @@ import {
useQuery,
useQueryClient,
useMutation,
-} from "@tanstack/react-query";
+} from '@tanstack/react-query'
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
-import "./styles.css";
+import './styles.css'
-let id = 0;
+let id = 0
let list = [
- "apple",
- "banana",
- "pineapple",
- "grapefruit",
- "dragonfruit",
- "grapes",
-].map((d) => ({ id: id++, name: d, notes: "These are some notes" }));
+ 'apple',
+ 'banana',
+ 'pineapple',
+ 'grapefruit',
+ 'dragonfruit',
+ 'grapes',
+].map((d) => ({ id: id++, name: d, notes: 'These are some notes' }))
-let errorRate = 0.05;
-let queryTimeMin = 1000;
-let queryTimeMax = 2000;
+let errorRate = 0.05
+let queryTimeMin = 1000
+let queryTimeMax = 2000
-const queryClient = new QueryClient();
+const queryClient = new QueryClient()
function Root() {
- const [staleTime, setStaleTime] = React.useState(1000);
- const [gcTime, setgcTime] = React.useState(3000);
- const [localErrorRate, setErrorRate] = React.useState(errorRate);
- const [localFetchTimeMin, setLocalFetchTimeMin] =
- React.useState(queryTimeMin);
- const [localFetchTimeMax, setLocalFetchTimeMax] =
- React.useState(queryTimeMax);
+ const [staleTime, setStaleTime] = React.useState(1000)
+ const [gcTime, setgcTime] = React.useState(3000)
+ const [localErrorRate, setErrorRate] = React.useState(errorRate)
+ const [localFetchTimeMin, setLocalFetchTimeMin] = React.useState(queryTimeMin)
+ const [localFetchTimeMax, setLocalFetchTimeMax] = React.useState(queryTimeMax)
React.useEffect(() => {
- errorRate = localErrorRate;
- queryTimeMin = localFetchTimeMin;
- queryTimeMax = localFetchTimeMax;
- }, [localErrorRate, localFetchTimeMax, localFetchTimeMin]);
+ errorRate = localErrorRate
+ queryTimeMin = localFetchTimeMin
+ queryTimeMax = localFetchTimeMax
+ }, [localErrorRate, localFetchTimeMax, localFetchTimeMin])
React.useEffect(() => {
queryClient.setDefaultOptions({
@@ -50,8 +48,8 @@ function Root() {
staleTime,
gcTime,
},
- });
- }, [gcTime, staleTime]);
+ })
+ }, [gcTime, staleTime])
return (
@@ -60,30 +58,30 @@ function Root() {
to show how query stale-ness and query caching work on a granular level
- Stale Time:{" "}
+ Stale Time:{' '}
setStaleTime(parseFloat(e.target.value, 10))}
- style={{ width: "100px" }}
+ style={{ width: '100px' }}
/>
- Garbage collection Time:{" "}
+ Garbage collection Time:{' '}
setgcTime(parseFloat(e.target.value, 10))}
- style={{ width: "100px" }}
+ style={{ width: '100px' }}
/>
- Error Rate:{" "}
+ Error Rate:{' '}
setErrorRate(parseFloat(e.target.value, 10))}
- style={{ width: "100px" }}
+ style={{ width: '100px' }}
/>
- Fetch Time Min:{" "}
+ Fetch Time Min:{' '}
setLocalFetchTimeMin(parseFloat(e.target.value, 10))}
- style={{ width: "60px" }}
- />{" "}
+ style={{ width: '60px' }}
+ />{' '}
- Fetch Time Max:{" "}
+ Fetch Time Max:{' '}
setLocalFetchTimeMax(parseFloat(e.target.value, 10))}
- style={{ width: "60px" }}
+ style={{ width: '60px' }}
/>
@@ -121,13 +119,13 @@ function Root() {
- );
+ )
}
function App() {
- const queryClient = useQueryClient();
- const [editingIndex, setEditingIndex] = React.useState(null);
- const [views, setViews] = React.useState(["", "fruit", "grape"]);
+ const queryClient = useQueryClient()
+ const [editingIndex, setEditingIndex] = React.useState(null)
+ const [views, setViews] = React.useState(['', 'fruit', 'grape'])
// const [views, setViews] = React.useState([""]);
return (
@@ -145,7 +143,7 @@ function App() {
initialFilter={view}
setEditingIndex={setEditingIndex}
onRemove={() => {
- setViews((old) => [...old, ""]);
+ setViews((old) => [...old, ''])
}}
/>
@@ -153,7 +151,7 @@ function App() {
))}
{
- setViews((old) => [...old, ""]);
+ setViews((old) => [...old, ''])
}}
>
Add Filter List
@@ -170,28 +168,28 @@ function App() {
) : null}
- );
+ )
}
-function Todos({ initialFilter = "", setEditingIndex }) {
- const [filter, setFilter] = React.useState(initialFilter);
+function Todos({ initialFilter = '', setEditingIndex }) {
+ const [filter, setFilter] = React.useState(initialFilter)
const { status, data, isFetching, error, failureCount, refetch } = useQuery({
- queryKey: ["todos", { filter }],
+ queryKey: ['todos', { filter }],
queryFn: fetchTodos,
- });
+ })
return (
- Filter:{" "}
+ Filter:{' '}
setFilter(e.target.value)} />
- {status === "pending" ? (
+ {status === 'pending' ? (
Loading... (Attempt: {failureCount + 1})
- ) : status === "error" ? (
+ ) : status === 'error' ? (
Error: {error.message}
@@ -203,7 +201,7 @@ function Todos({ initialFilter = "", setEditingIndex }) {
{data
? data.map((todo) => (
- {todo.name}{" "}
+ {todo.name}{' '}
setEditingIndex(todo.id)}>
Edit
@@ -223,44 +221,44 @@ function Todos({ initialFilter = "", setEditingIndex }) {
>
)}
- );
+ )
}
function EditTodo({ editingIndex, setEditingIndex }) {
- const queryClient = useQueryClient();
+ const queryClient = useQueryClient()
// Don't attempt to query until editingIndex is truthy
const { status, data, isFetching, error, failureCount, refetch } = useQuery({
- queryKey: ["todo", { id: editingIndex }],
+ queryKey: ['todo', { id: editingIndex }],
queryFn: () => fetchTodoById({ id: editingIndex }),
enabled: editingIndex !== null,
- });
+ })
- const [todo, setTodo] = React.useState(data || {});
+ const [todo, setTodo] = React.useState(data || {})
React.useEffect(() => {
if (editingIndex !== null && data) {
- setTodo(data);
+ setTodo(data)
} else {
- setTodo({});
+ setTodo({})
}
- }, [data, editingIndex]);
+ }, [data, editingIndex])
const saveMutation = useMutation({
mutationFn: patchTodo,
onSuccess: (data) => {
// Update `todos` and the individual todo queries when this mutation succeeds
- queryClient.invalidateQueries({ queryKey: ["todos"] });
- queryClient.setQueryData(["todo", { id: editingIndex }], data);
+ queryClient.invalidateQueries({ queryKey: ['todos'] })
+ queryClient.setQueryData(['todo', { id: editingIndex }], data)
},
- });
+ })
const onSave = () => {
- saveMutation.mutate(todo);
- };
+ saveMutation.mutate(todo)
+ }
const disableEditSave =
- status === "pending" || saveMutation.status === "pending";
+ status === 'pending' || saveMutation.status === 'pending'
return (
@@ -273,7 +271,7 @@ function EditTodo({ editingIndex, setEditingIndex }) {
>
) : null}
- {status === "pending" ? (
+ {status === 'pending' ? (
Loading... (Attempt: {failureCount + 1})
) : error ? (
@@ -282,7 +280,7 @@ function EditTodo({ editingIndex, setEditingIndex }) {
) : (
<>
- Name:{" "}
+ Name:{' '}
@@ -293,7 +291,7 @@ function EditTodo({ editingIndex, setEditingIndex }) {
/>
- Notes:{" "}
+ Notes:{' '}
@@ -309,11 +307,11 @@ function EditTodo({ editingIndex, setEditingIndex }) {
- {saveMutation.status === "pending"
- ? "Saving..."
- : saveMutation.status === "error"
+ {saveMutation.status === 'pending'
+ ? 'Saving...'
+ : saveMutation.status === 'error'
? saveMutation.error.message
- : "Saved!"}
+ : 'Saved!'}
{isFetching ? (
@@ -327,114 +325,114 @@ function EditTodo({ editingIndex, setEditingIndex }) {
>
)}
- );
+ )
}
function AddTodo() {
- const queryClient = useQueryClient();
- const [name, setName] = React.useState("");
+ const queryClient = useQueryClient()
+ const [name, setName] = React.useState('')
const addMutation = useMutation({
mutationFn: postTodo,
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["todos"] });
+ queryClient.invalidateQueries({ queryKey: ['todos'] })
},
- });
+ })
return (
- );
+ )
}
function fetchTodos({ signal, queryKey: [, { filter }] }) {
- console.info("fetchTodos", { filter });
+ console.info('fetchTodos', { filter })
if (signal) {
- signal.addEventListener("abort", () => {
- console.info("cancelled", filter);
- });
+ signal.addEventListener('abort', () => {
+ console.info('cancelled', filter)
+ })
}
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < errorRate) {
return reject(
- new Error(JSON.stringify({ fetchTodos: { filter } }, null, 2))
- );
+ new Error(JSON.stringify({ fetchTodos: { filter } }, null, 2)),
+ )
}
- resolve(list.filter((d) => d.name.includes(filter)));
- }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
- });
+ resolve(list.filter((d) => d.name.includes(filter)))
+ }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin))
+ })
}
function fetchTodoById({ id }) {
- console.info("fetchTodoById", { id });
+ console.info('fetchTodoById', { id })
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < errorRate) {
return reject(
- new Error(JSON.stringify({ fetchTodoById: { id } }, null, 2))
- );
+ new Error(JSON.stringify({ fetchTodoById: { id } }, null, 2)),
+ )
}
- resolve(list.find((d) => d.id === id));
- }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
- });
+ resolve(list.find((d) => d.id === id))
+ }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin))
+ })
}
function postTodo({ name, notes }) {
- console.info("postTodo", { name, notes });
+ console.info('postTodo', { name, notes })
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < errorRate) {
return reject(
- new Error(JSON.stringify({ postTodo: { name, notes } }, null, 2))
- );
+ new Error(JSON.stringify({ postTodo: { name, notes } }, null, 2)),
+ )
}
- const todo = { name, notes, id: id++ };
- list = [...list, todo];
- resolve(todo);
- }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
- });
+ const todo = { name, notes, id: id++ }
+ list = [...list, todo]
+ resolve(todo)
+ }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin))
+ })
}
function patchTodo(todo) {
- console.info("patchTodo", todo);
+ console.info('patchTodo', todo)
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < errorRate) {
- return reject(new Error(JSON.stringify({ patchTodo: todo }, null, 2)));
+ return reject(new Error(JSON.stringify({ patchTodo: todo }, null, 2)))
}
list = list.map((d) => {
if (d.id === todo.id) {
- return todo;
+ return todo
}
- return d;
- });
- resolve(todo);
- }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin));
- });
+ return d
+ })
+ resolve(todo)
+ }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin))
+ })
}
-const rootElement = document.getElementById("root");
-ReactDOM.createRoot(rootElement).render( );
+const rootElement = document.getElementById('root')
+ReactDOM.createRoot(rootElement).render( )
diff --git a/examples/react/prefetching/pages/[user]/[repo].js b/examples/react/prefetching/src/pages/[user]/[repo].js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/prefetching/pages/[user]/[repo].js
rename to examples/react/prefetching/src/pages/[user]/[repo].js
diff --git a/examples/react/prefetching/pages/api/data.js b/examples/react/prefetching/src/pages/api/data.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/prefetching/pages/api/data.js
rename to examples/react/prefetching/src/pages/api/data.js
diff --git a/examples/react/prefetching/pages/index.js b/examples/react/prefetching/src/pages/index.js
old mode 100755
new mode 100644
similarity index 100%
rename from examples/react/prefetching/pages/index.js
rename to examples/react/prefetching/src/pages/index.js
diff --git a/examples/react/react-native/.prettierrc b/examples/react/react-native/.prettierrc
deleted file mode 100644
index 8281770389..0000000000
--- a/examples/react/react-native/.prettierrc
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "printWidth": 80,
- "semi": true,
- "singleQuote": true,
- "tabWidth": 2,
- "useTabs": false,
- "trailingComma": "es5"
-}
diff --git a/examples/react/react-native/App.tsx b/examples/react/react-native/App.tsx
index fa5ab360aa..fa5103e2de 100644
--- a/examples/react/react-native/App.tsx
+++ b/examples/react/react-native/App.tsx
@@ -1,31 +1,31 @@
-import * as React from 'react';
-import { AppStateStatus, Platform } from 'react-native';
-import { NavigationContainer } from '@react-navigation/native';
+import * as React from 'react'
+import { AppStateStatus, Platform } from 'react-native'
+import { NavigationContainer } from '@react-navigation/native'
import {
QueryClient,
QueryClientProvider,
focusManager,
-} from '@tanstack/react-query';
+} from '@tanstack/react-query'
-import { useAppState } from './src/hooks/useAppState';
-import { MoviesStack } from './src/navigation/MoviesStack';
-import { useOnlineManager } from './src/hooks/useOnlineManager';
+import { useAppState } from './src/hooks/useAppState'
+import { MoviesStack } from './src/navigation/MoviesStack'
+import { useOnlineManager } from './src/hooks/useOnlineManager'
function onAppStateChange(status: AppStateStatus) {
// React Query already supports in web browser refetch on window focus by default
if (Platform.OS !== 'web') {
- focusManager.setFocused(status === 'active');
+ focusManager.setFocused(status === 'active')
}
}
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 2 } },
-});
+})
export default function App() {
- useOnlineManager();
+ useOnlineManager()
- useAppState(onAppStateChange);
+ useAppState(onAppStateChange)
return (
@@ -33,5 +33,5 @@ export default function App() {
- );
+ )
}
diff --git a/examples/react/react-native/babel.config.js b/examples/react/react-native/babel.config.js
index 9d89e13119..e1e3637afd 100644
--- a/examples/react/react-native/babel.config.js
+++ b/examples/react/react-native/babel.config.js
@@ -1,6 +1,6 @@
module.exports = function (api) {
- api.cache(true);
+ api.cache(true)
return {
presets: ['babel-preset-expo'],
- };
-};
+ }
+}
diff --git a/examples/react/react-native/src/components/Divider.tsx b/examples/react/react-native/src/components/Divider.tsx
index 7c3b5fa831..1ea2ee3839 100644
--- a/examples/react/react-native/src/components/Divider.tsx
+++ b/examples/react/react-native/src/components/Divider.tsx
@@ -1,13 +1,13 @@
-import * as React from 'react';
-import { StyleSheet } from 'react-native';
-import { Divider as PaperDivider } from 'react-native-paper';
+import * as React from 'react'
+import { StyleSheet } from 'react-native'
+import { Divider as PaperDivider } from 'react-native-paper'
export function Divider() {
- return ;
+ return
}
const styles = StyleSheet.create({
divider: {
marginLeft: 10,
},
-});
+})
diff --git a/examples/react/react-native/src/components/ErrorMessage.tsx b/examples/react/react-native/src/components/ErrorMessage.tsx
index b7e3f2fb5b..dd56c6649f 100644
--- a/examples/react/react-native/src/components/ErrorMessage.tsx
+++ b/examples/react/react-native/src/components/ErrorMessage.tsx
@@ -1,16 +1,16 @@
-import * as React from 'react';
-import { Text, View, StyleSheet } from 'react-native';
+import * as React from 'react'
+import { Text, View, StyleSheet } from 'react-native'
type Props = {
- message: string;
-};
+ message: string
+}
export function ErrorMessage({ message }: Props) {
return (
{message}
- );
+ )
}
const styles = StyleSheet.create({
@@ -19,4 +19,4 @@ const styles = StyleSheet.create({
justifyContent: 'center',
alignItems: 'center',
},
-});
+})
diff --git a/examples/react/react-native/src/components/ListItem.tsx b/examples/react/react-native/src/components/ListItem.tsx
index b6d0e2b546..ee52729efd 100644
--- a/examples/react/react-native/src/components/ListItem.tsx
+++ b/examples/react/react-native/src/components/ListItem.tsx
@@ -1,11 +1,11 @@
-import * as React from 'react';
-import { View, StyleSheet } from 'react-native';
-import { Paragraph, TouchableRipple } from 'react-native-paper';
+import * as React from 'react'
+import { View, StyleSheet } from 'react-native'
+import { Paragraph, TouchableRipple } from 'react-native-paper'
type Props = {
- item: any;
- onPress: (item: any) => void;
-};
+ item: any
+ onPress: (item: any) => void
+}
export function ListItem({ item, onPress }: Props) {
return (
@@ -19,7 +19,7 @@ export function ListItem({ item, onPress }: Props) {
- );
+ )
}
const styles = StyleSheet.create({
@@ -38,4 +38,4 @@ const styles = StyleSheet.create({
marginBottom: 10,
},
title: { fontWeight: 'bold' },
-});
+})
diff --git a/examples/react/react-native/src/components/LoadingIndicator.tsx b/examples/react/react-native/src/components/LoadingIndicator.tsx
index 1068cbcf50..7bcdd99253 100644
--- a/examples/react/react-native/src/components/LoadingIndicator.tsx
+++ b/examples/react/react-native/src/components/LoadingIndicator.tsx
@@ -1,12 +1,12 @@
-import * as React from 'react';
-import { ActivityIndicator, View, StyleSheet } from 'react-native';
+import * as React from 'react'
+import { ActivityIndicator, View, StyleSheet } from 'react-native'
export function LoadingIndicator() {
return (
- );
+ )
}
const styles = StyleSheet.create({
@@ -15,4 +15,4 @@ const styles = StyleSheet.create({
justifyContent: 'center',
alignItems: 'center',
},
-});
+})
diff --git a/examples/react/react-native/src/hooks/useAppState.ts b/examples/react/react-native/src/hooks/useAppState.ts
index eca5209a0a..2aad30f9ec 100644
--- a/examples/react/react-native/src/hooks/useAppState.ts
+++ b/examples/react/react-native/src/hooks/useAppState.ts
@@ -1,11 +1,11 @@
-import { useEffect } from 'react';
-import { AppState, AppStateStatus } from 'react-native';
+import { useEffect } from 'react'
+import { AppState, AppStateStatus } from 'react-native'
export function useAppState(onChange: (status: AppStateStatus) => void) {
useEffect(() => {
- AppState.addEventListener('change', onChange);
+ AppState.addEventListener('change', onChange)
return () => {
- AppState.removeEventListener('change', onChange);
- };
- }, [onChange]);
+ AppState.removeEventListener('change', onChange)
+ }
+ }, [onChange])
}
diff --git a/examples/react/react-native/src/hooks/useOnlineManager.ts b/examples/react/react-native/src/hooks/useOnlineManager.ts
index f6c9737bfe..ecaf74512e 100644
--- a/examples/react/react-native/src/hooks/useOnlineManager.ts
+++ b/examples/react/react-native/src/hooks/useOnlineManager.ts
@@ -1,7 +1,7 @@
-import * as React from 'react';
-import NetInfo from '@react-native-community/netinfo';
-import { onlineManager } from '@tanstack/react-query';
-import { Platform } from 'react-native';
+import * as React from 'react'
+import NetInfo from '@react-native-community/netinfo'
+import { onlineManager } from '@tanstack/react-query'
+import { Platform } from 'react-native'
export function useOnlineManager() {
React.useEffect(() => {
@@ -11,9 +11,9 @@ export function useOnlineManager() {
onlineManager.setOnline(
state.isConnected != null &&
state.isConnected &&
- Boolean(state.isInternetReachable)
- );
- });
+ Boolean(state.isInternetReachable),
+ )
+ })
}
- }, []);
+ }, [])
}
diff --git a/examples/react/react-native/src/hooks/useRefreshByUser.ts b/examples/react/react-native/src/hooks/useRefreshByUser.ts
index 44a561ca30..46fcea58a1 100644
--- a/examples/react/react-native/src/hooks/useRefreshByUser.ts
+++ b/examples/react/react-native/src/hooks/useRefreshByUser.ts
@@ -1,20 +1,20 @@
-import * as React from 'react';
+import * as React from 'react'
export function useRefreshByUser(refetch: () => Promise) {
- const [isRefetchingByUser, setIsRefetchingByUser] = React.useState(false);
+ const [isRefetchingByUser, setIsRefetchingByUser] = React.useState(false)
async function refetchByUser() {
- setIsRefetchingByUser(true);
+ setIsRefetchingByUser(true)
try {
- await refetch();
+ await refetch()
} finally {
- setIsRefetchingByUser(false);
+ setIsRefetchingByUser(false)
}
}
return {
isRefetchingByUser,
refetchByUser,
- };
+ }
}
diff --git a/examples/react/react-native/src/hooks/useRefreshOnFocus.ts b/examples/react/react-native/src/hooks/useRefreshOnFocus.ts
index a8e93a44eb..dd9cbd3ea1 100644
--- a/examples/react/react-native/src/hooks/useRefreshOnFocus.ts
+++ b/examples/react/react-native/src/hooks/useRefreshOnFocus.ts
@@ -1,16 +1,16 @@
-import * as React from 'react';
-import { useFocusEffect } from '@react-navigation/native';
+import * as React from 'react'
+import { useFocusEffect } from '@react-navigation/native'
export function useRefreshOnFocus(refetch: () => void) {
- const enabledRef = React.useRef(false);
+ const enabledRef = React.useRef(false)
useFocusEffect(
React.useCallback(() => {
if (enabledRef.current) {
- refetch();
+ refetch()
} else {
- enabledRef.current = true;
+ enabledRef.current = true
}
- }, [refetch])
- );
+ }, [refetch]),
+ )
}
diff --git a/examples/react/react-native/src/lib/api.ts b/examples/react/react-native/src/lib/api.ts
index 2cc654b89e..fe7f2c927c 100644
--- a/examples/react/react-native/src/lib/api.ts
+++ b/examples/react/react-native/src/lib/api.ts
@@ -1,44 +1,44 @@
-import movies from '../data/movies.json';
+import movies from '../data/movies.json'
export type Movie = {
- title: string;
- year: number;
-};
+ title: string
+ year: number
+}
export type MovieDetails = Movie & {
info: {
- plot: string;
- actors: string[];
- };
-};
+ plot: string
+ actors: string[]
+ }
+}
function delay(t: number) {
return new Promise(function (resolve) {
- setTimeout(resolve, t);
- });
+ setTimeout(resolve, t)
+ })
}
export async function fetchMovies() {
- console.log('fetchMovies');
+ console.log('fetchMovies')
- await delay(200 + Math.floor(Math.random() * 2000));
+ await delay(200 + Math.floor(Math.random() * 2000))
return movies
.slice(0, 100)
.map((movie) => ({ title: movie.title, year: movie.year })) as Promise<
Movie[]
- >;
+ >
}
export async function fetchMovie(title: string) {
- console.log('fetchMovie', title);
+ console.log('fetchMovie', title)
- await delay(200 + Math.floor(Math.random() * 2000));
+ await delay(200 + Math.floor(Math.random() * 2000))
- const result = movies.filter((item) => item.title === title);
+ const result = movies.filter((item) => item.title === title)
if (result.length == 0) {
- throw new Error('Movie not found');
+ throw new Error('Movie not found')
}
- return result[0] as Promise;
+ return result[0] as Promise
}
diff --git a/examples/react/react-native/src/navigation/MoviesStack.tsx b/examples/react/react-native/src/navigation/MoviesStack.tsx
index 69f7851458..364126feb9 100644
--- a/examples/react/react-native/src/navigation/MoviesStack.tsx
+++ b/examples/react/react-native/src/navigation/MoviesStack.tsx
@@ -1,11 +1,11 @@
-import * as React from 'react';
-import { createStackNavigator } from '@react-navigation/stack';
+import * as React from 'react'
+import { createStackNavigator } from '@react-navigation/stack'
-import { MoviesListScreen } from '../screens/MoviesListScreen';
-import { MovieDetailsScreen } from '../screens/MovieDetailsScreen';
-import { MoviesStackNavigator } from './types';
+import { MoviesListScreen } from '../screens/MoviesListScreen'
+import { MovieDetailsScreen } from '../screens/MovieDetailsScreen'
+import { MoviesStackNavigator } from './types'
-const Stack = createStackNavigator();
+const Stack = createStackNavigator()
export function MoviesStack() {
return (
@@ -25,5 +25,5 @@ export function MoviesStack() {
}}
/>
- );
+ )
}
diff --git a/examples/react/react-native/src/navigation/types.ts b/examples/react/react-native/src/navigation/types.ts
index a8f4c28d06..2967bf0d5c 100644
--- a/examples/react/react-native/src/navigation/types.ts
+++ b/examples/react/react-native/src/navigation/types.ts
@@ -1,6 +1,6 @@
-import { Movie } from '../lib/api';
+import { Movie } from '../lib/api'
export type MoviesStackNavigator = {
- MoviesList: undefined;
- MovieDetails: { movie: Movie };
-};
+ MoviesList: undefined
+ MovieDetails: { movie: Movie }
+}
diff --git a/examples/react/react-native/src/screens/MovieDetailsScreen.tsx b/examples/react/react-native/src/screens/MovieDetailsScreen.tsx
index d95d96cc19..643968fb56 100644
--- a/examples/react/react-native/src/screens/MovieDetailsScreen.tsx
+++ b/examples/react/react-native/src/screens/MovieDetailsScreen.tsx
@@ -1,38 +1,38 @@
-import * as React from 'react';
-import { View, RefreshControl, StyleSheet, ScrollView } from 'react-native';
-import { Title, Paragraph } from 'react-native-paper';
-import { StackNavigationProp } from '@react-navigation/stack';
-import { RouteProp } from '@react-navigation/native';
-import { useQuery } from '@tanstack/react-query';
+import * as React from 'react'
+import { View, RefreshControl, StyleSheet, ScrollView } from 'react-native'
+import { Title, Paragraph } from 'react-native-paper'
+import { StackNavigationProp } from '@react-navigation/stack'
+import { RouteProp } from '@react-navigation/native'
+import { useQuery } from '@tanstack/react-query'
-import { LoadingIndicator } from '../components/LoadingIndicator';
-import { ErrorMessage } from '../components/ErrorMessage';
-import { useRefreshByUser } from '../hooks/useRefreshByUser';
-import { fetchMovie, MovieDetails } from '../lib/api';
-import type { MoviesStackNavigator } from '../navigation/types';
+import { LoadingIndicator } from '../components/LoadingIndicator'
+import { ErrorMessage } from '../components/ErrorMessage'
+import { useRefreshByUser } from '../hooks/useRefreshByUser'
+import { fetchMovie, MovieDetails } from '../lib/api'
+import type { MoviesStackNavigator } from '../navigation/types'
type MoviesDetailsScreenNavigationProp = StackNavigationProp<
MoviesStackNavigator,
'MovieDetails'
->;
+>
type Props = {
- navigation: MoviesDetailsScreenNavigationProp;
- route: RouteProp;
-};
+ navigation: MoviesDetailsScreenNavigationProp
+ route: RouteProp
+}
export function MovieDetailsScreen({ route }: Props) {
const { isPending, error, data, refetch } = useQuery({
queryKey: ['movie', route.params.movie.title],
queryFn: () => fetchMovie(route.params.movie.title),
initialData: route.params.movie as MovieDetails,
- });
+ })
- const { isRefetchingByUser, refetchByUser } = useRefreshByUser(refetch);
+ const { isRefetchingByUser, refetchByUser } = useRefreshByUser(refetch)
- if (isPending) return ;
- if (error) return ;
- if (!data) return null;
+ if (isPending) return
+ if (error) return
+ if (!data) return null
return (
)}
- );
+ )
}
const styles = StyleSheet.create({
@@ -82,4 +82,4 @@ const styles = StyleSheet.create({
margin: 20,
marginTop: 10,
},
-});
+})
diff --git a/examples/react/react-native/src/screens/MoviesListScreen.tsx b/examples/react/react-native/src/screens/MoviesListScreen.tsx
index 118ed50bb4..3bc8a37d25 100644
--- a/examples/react/react-native/src/screens/MoviesListScreen.tsx
+++ b/examples/react/react-native/src/screens/MoviesListScreen.tsx
@@ -1,53 +1,53 @@
-import * as React from 'react';
-import { FlatList, RefreshControl } from 'react-native';
-import { useQuery } from '@tanstack/react-query';
+import * as React from 'react'
+import { FlatList, RefreshControl } from 'react-native'
+import { useQuery } from '@tanstack/react-query'
-import { StackNavigationProp } from '@react-navigation/stack';
-import { LoadingIndicator } from '../components/LoadingIndicator';
-import { ErrorMessage } from '../components/ErrorMessage';
-import { Divider } from '../components/Divider';
-import { ListItem } from '../components/ListItem';
-import { useRefreshByUser } from '../hooks/useRefreshByUser';
-import { useRefreshOnFocus } from '../hooks/useRefreshOnFocus';
-import { fetchMovies, Movie } from '../lib/api';
-import { MoviesStackNavigator } from '../navigation/types';
+import { StackNavigationProp } from '@react-navigation/stack'
+import { LoadingIndicator } from '../components/LoadingIndicator'
+import { ErrorMessage } from '../components/ErrorMessage'
+import { Divider } from '../components/Divider'
+import { ListItem } from '../components/ListItem'
+import { useRefreshByUser } from '../hooks/useRefreshByUser'
+import { useRefreshOnFocus } from '../hooks/useRefreshOnFocus'
+import { fetchMovies, Movie } from '../lib/api'
+import { MoviesStackNavigator } from '../navigation/types'
type MoviesListScreenNavigationProp = StackNavigationProp<
MoviesStackNavigator,
'MoviesList'
->;
+>
type Props = {
- navigation: MoviesListScreenNavigationProp;
-};
+ navigation: MoviesListScreenNavigationProp
+}
export function MoviesListScreen({ navigation }: Props) {
const { isPending, error, data, refetch } = useQuery({
queryKey: ['movies'],
queryFn: fetchMovies,
- });
- const { isRefetchingByUser, refetchByUser } = useRefreshByUser(refetch);
- useRefreshOnFocus(refetch);
+ })
+ const { isRefetchingByUser, refetchByUser } = useRefreshByUser(refetch)
+ useRefreshOnFocus(refetch)
const onListItemPress = React.useCallback(
(movie) => {
navigation.navigate('MovieDetails', {
movie,
- });
+ })
},
- [navigation]
- );
+ [navigation],
+ )
const renderItem = React.useCallback(
({ item }) => {
- return ;
+ return
},
- [onListItemPress]
- );
+ [onListItemPress],
+ )
- if (isPending) return ;
+ if (isPending) return
- if (error) return ;
+ if (error) return
return (
}
>
- );
+ )
}
diff --git a/examples/react/react-router/.prettierrc b/examples/react/react-router/.prettierrc
deleted file mode 100644
index 0967ef424b..0000000000
--- a/examples/react/react-router/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/examples/react/react-router/src/contacts.js b/examples/react/react-router/src/contacts.js
index 78114e0a64..ab9c66599c 100644
--- a/examples/react/react-router/src/contacts.js
+++ b/examples/react/react-router/src/contacts.js
@@ -1,92 +1,92 @@
-import localforage from "localforage";
-import { matchSorter } from "match-sorter";
-import sortBy from "sort-by";
+import localforage from 'localforage'
+import { matchSorter } from 'match-sorter'
+import sortBy from 'sort-by'
const seed = async () => {
const initialData = [
{
- avatar: "https://avatars.githubusercontent.com/u/5580297?v=4",
+ avatar: 'https://avatars.githubusercontent.com/u/5580297?v=4',
createdAt: 1660978713047,
favorite: false,
- first: "Tanner",
- id: "usupkc1",
- last: "Linsley",
- notes: "Created React Query",
- twitter: "@tannerlinsley",
+ first: 'Tanner',
+ id: 'usupkc1',
+ last: 'Linsley',
+ notes: 'Created React Query',
+ twitter: '@tannerlinsley',
},
{
- avatar: "https://avatars.githubusercontent.com/u/1021430",
+ avatar: 'https://avatars.githubusercontent.com/u/1021430',
createdAt: 1660979124264,
favorite: false,
- first: "Dominik",
- id: "kvvztl7",
- last: "D",
- notes: "Maintains React Query",
- twitter: "@tkdodo",
+ first: 'Dominik',
+ id: 'kvvztl7',
+ last: 'D',
+ notes: 'Maintains React Query',
+ twitter: '@tkdodo',
},
- ];
- const contacts = await localforage.getItem("contacts");
+ ]
+ const contacts = await localforage.getItem('contacts')
if (!contacts) {
- set(initialData);
+ set(initialData)
}
-};
+}
-seed();
+seed()
export async function getContacts(query) {
- await fakeNetwork(`getContacts:${query}`);
- let contacts = await localforage.getItem("contacts");
- if (!contacts) contacts = [];
+ await fakeNetwork(`getContacts:${query}`)
+ let contacts = await localforage.getItem('contacts')
+ if (!contacts) contacts = []
if (query) {
- contacts = matchSorter(contacts, query, { keys: ["first", "last"] });
+ contacts = matchSorter(contacts, query, { keys: ['first', 'last'] })
}
- return contacts.sort(sortBy("last", "createdAt"));
+ return contacts.sort(sortBy('last', 'createdAt'))
}
export async function createContact() {
- await fakeNetwork();
- let id = Math.random().toString(36).substring(2, 9);
- let contact = { id, createdAt: Date.now() };
- let contacts = await getContacts();
- contacts.unshift(contact);
- await set(contacts);
- return contact;
+ await fakeNetwork()
+ let id = Math.random().toString(36).substring(2, 9)
+ let contact = { id, createdAt: Date.now() }
+ let contacts = await getContacts()
+ contacts.unshift(contact)
+ await set(contacts)
+ return contact
}
export async function getContact(id) {
- await fakeNetwork(`contact:${id}`);
- let contacts = await localforage.getItem("contacts");
- let contact = contacts.find((contact) => contact.id === id);
- return contact ?? null;
+ await fakeNetwork(`contact:${id}`)
+ let contacts = await localforage.getItem('contacts')
+ let contact = contacts.find((contact) => contact.id === id)
+ return contact ?? null
}
export async function updateContact(id, updates) {
- await fakeNetwork();
- let contacts = await localforage.getItem("contacts");
- let contact = contacts.find((contact) => contact.id === id);
- if (!contact) throw new Error("No contact found for", id);
- Object.assign(contact, updates);
- await set(contacts);
- return contact;
+ await fakeNetwork()
+ let contacts = await localforage.getItem('contacts')
+ let contact = contacts.find((contact) => contact.id === id)
+ if (!contact) throw new Error('No contact found for', id)
+ Object.assign(contact, updates)
+ await set(contacts)
+ return contact
}
export async function deleteContact(id) {
- let contacts = await localforage.getItem("contacts");
- let index = contacts.findIndex((contact) => contact.id === id);
+ let contacts = await localforage.getItem('contacts')
+ let index = contacts.findIndex((contact) => contact.id === id)
if (index > -1) {
- contacts.splice(index, 1);
- await set(contacts);
- return true;
+ contacts.splice(index, 1)
+ await set(contacts)
+ return true
}
- return false;
+ return false
}
function set(contacts) {
- return localforage.setItem("contacts", contacts);
+ return localforage.setItem('contacts', contacts)
}
async function fakeNetwork() {
return new Promise((res) => {
- setTimeout(res, Math.random() * 800);
- });
+ setTimeout(res, Math.random() * 800)
+ })
}
diff --git a/examples/react/react-router/src/error-page.jsx b/examples/react/react-router/src/error-page.jsx
index 17c83baa8c..19e7d42087 100644
--- a/examples/react/react-router/src/error-page.jsx
+++ b/examples/react/react-router/src/error-page.jsx
@@ -1,9 +1,9 @@
-import * as React from "react";
-import { useRouteError } from "react-router-dom";
+import * as React from 'react'
+import { useRouteError } from 'react-router-dom'
export default function ErrorPage() {
- const error = useRouteError();
- console.error(error);
+ const error = useRouteError()
+ console.error(error)
return (
@@ -13,5 +13,5 @@ export default function ErrorPage() {
{error.statusText || error.message}
- );
+ )
}
diff --git a/examples/react/react-router/src/index.jsx b/examples/react/react-router/src/index.jsx
index edae2fcde1..0482c714d0 100644
--- a/examples/react/react-router/src/index.jsx
+++ b/examples/react/react-router/src/index.jsx
@@ -1,23 +1,20 @@
-import * as React from "react";
-import * as ReactDOM from "react-dom/client";
-import { createBrowserRouter, RouterProvider } from "react-router-dom";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
+import * as React from 'react'
+import * as ReactDOM from 'react-dom/client'
+import { createBrowserRouter, RouterProvider } from 'react-router-dom'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
-import "./index.css";
+import './index.css'
-import ErrorPage from "./error-page";
-import Root, {
- loader as rootLoader,
- action as rootAction,
-} from "./routes/root";
+import ErrorPage from './error-page'
+import Root, { loader as rootLoader, action as rootAction } from './routes/root'
import Contact, {
loader as contactLoader,
action as contactAction,
-} from "./routes/contact";
-import EditContact, { action as editAction } from "./routes/edit";
-import { action as destroyAction } from "./routes/destroy";
-import Index from "./routes/index";
+} from './routes/contact'
+import EditContact, { action as editAction } from './routes/edit'
+import { action as destroyAction } from './routes/destroy'
+import Index from './routes/index'
const queryClient = new QueryClient({
defaultOptions: {
@@ -25,11 +22,11 @@ const queryClient = new QueryClient({
staleTime: 1000 * 10,
},
},
-});
+})
const router = createBrowserRouter([
{
- path: "/",
+ path: '/',
element: ,
errorElement: ,
loader: rootLoader(queryClient),
@@ -40,33 +37,33 @@ const router = createBrowserRouter([
element: ,
},
{
- path: "contacts/:contactId",
+ path: 'contacts/:contactId',
element: ,
loader: contactLoader(queryClient),
action: contactAction(queryClient),
},
{
- path: "contacts/:contactId/edit",
+ path: 'contacts/:contactId/edit',
element: ,
loader: contactLoader(queryClient),
action: editAction(queryClient),
},
{
- path: "contacts/:contactId/destroy",
+ path: 'contacts/:contactId/destroy',
element: ,
action: destroyAction(queryClient),
errorElement: Oops! There was an error.
,
},
],
},
-]);
+])
-const rootElement = document.getElementById("root");
+const rootElement = document.getElementById('root')
ReactDOM.createRoot(rootElement).render(
-
-);
+ ,
+)
diff --git a/examples/react/react-router/src/routes/contact.jsx b/examples/react/react-router/src/routes/contact.jsx
index a841699a63..9164f1b55f 100644
--- a/examples/react/react-router/src/routes/contact.jsx
+++ b/examples/react/react-router/src/routes/contact.jsx
@@ -1,46 +1,46 @@
-import * as React from "react";
-import { Form, useFetcher, useParams } from "react-router-dom";
-import { getContact, updateContact } from "../contacts";
-import { useQuery } from "@tanstack/react-query";
+import * as React from 'react'
+import { Form, useFetcher, useParams } from 'react-router-dom'
+import { getContact, updateContact } from '../contacts'
+import { useQuery } from '@tanstack/react-query'
const contactDetailQuery = (id) => ({
- queryKey: ["contacts", "detail", id],
+ queryKey: ['contacts', 'detail', id],
queryFn: async () => {
- const contact = await getContact(id);
+ const contact = await getContact(id)
if (!contact) {
- throw new Response("", {
+ throw new Response('', {
status: 404,
- statusText: "Not Found",
- });
+ statusText: 'Not Found',
+ })
}
- return contact;
+ return contact
},
-});
+})
export const loader =
(queryClient) =>
async ({ params }) => {
- const query = contactDetailQuery(params.contactId);
+ const query = contactDetailQuery(params.contactId)
return (
queryClient.getQueryData(query.queryKey) ??
(await queryClient.fetchQuery(query))
- );
- };
+ )
+ }
export const action =
(queryClient) =>
async ({ request, params }) => {
- let formData = await request.formData();
+ let formData = await request.formData()
const contact = await updateContact(params.contactId, {
- favorite: formData.get("favorite") === "true",
- });
- await queryClient.invalidateQueries({ queryKey: ["contacts"] });
- return contact;
- };
+ favorite: formData.get('favorite') === 'true',
+ })
+ await queryClient.invalidateQueries({ queryKey: ['contacts'] })
+ return contact
+ }
export default function Contact() {
- const params = useParams();
- const { data: contact } = useQuery(contactDetailQuery(params.contactId));
+ const params = useParams()
+ const { data: contact } = useQuery(contactDetailQuery(params.contactId))
return (
@@ -56,7 +56,7 @@ export default function Contact() {
>
) : (
No Name
- )}{" "}
+ )}{' '}
@@ -79,8 +79,8 @@ export default function Contact() {
action="destroy"
onSubmit={(event) => {
// eslint-disable-next-line no-restricted-globals
- if (!confirm("Please confirm you want to delete this record.")) {
- event.preventDefault();
+ if (!confirm('Please confirm you want to delete this record.')) {
+ event.preventDefault()
}
}}
>
@@ -89,25 +89,25 @@ export default function Contact() {
- );
+ )
}
function Favorite({ contact }) {
- const fetcher = useFetcher();
- let favorite = contact.favorite;
+ const fetcher = useFetcher()
+ let favorite = contact.favorite
if (fetcher.formData) {
- favorite = fetcher.formData.get("favorite") === "true";
+ favorite = fetcher.formData.get('favorite') === 'true'
}
return (
- {favorite ? "★" : "☆"}
+ {favorite ? '★' : '☆'}
- );
+ )
}
diff --git a/examples/react/react-router/src/routes/destroy.jsx b/examples/react/react-router/src/routes/destroy.jsx
index 5b95f69b87..5b5f0cbc87 100644
--- a/examples/react/react-router/src/routes/destroy.jsx
+++ b/examples/react/react-router/src/routes/destroy.jsx
@@ -1,10 +1,10 @@
-import { redirect } from "react-router-dom";
-import { deleteContact } from "../contacts";
+import { redirect } from 'react-router-dom'
+import { deleteContact } from '../contacts'
export const action =
(queryClient) =>
async ({ params }) => {
- await deleteContact(params.contactId);
- queryClient.invalidateQueries({ queryKey: ["contacts"] });
- return redirect("/");
- };
+ await deleteContact(params.contactId)
+ queryClient.invalidateQueries({ queryKey: ['contacts'] })
+ return redirect('/')
+ }
diff --git a/examples/react/react-router/src/routes/edit.jsx b/examples/react/react-router/src/routes/edit.jsx
index f1d9c64f86..693083d9d0 100644
--- a/examples/react/react-router/src/routes/edit.jsx
+++ b/examples/react/react-router/src/routes/edit.jsx
@@ -1,21 +1,21 @@
-import * as React from "react";
-import { Form, useLoaderData, redirect, useNavigate } from "react-router-dom";
+import * as React from 'react'
+import { Form, useLoaderData, redirect, useNavigate } from 'react-router-dom'
-import { updateContact } from "../contacts";
+import { updateContact } from '../contacts'
export const action =
(queryClient) =>
async ({ request, params }) => {
- const formData = await request.formData();
- const updates = Object.fromEntries(formData);
- await updateContact(params.contactId, updates);
- queryClient.invalidateQueries({ queryKey: ["contacts"] });
- return redirect(`/contacts/${params.contactId}`);
- };
+ const formData = await request.formData()
+ const updates = Object.fromEntries(formData)
+ await updateContact(params.contactId, updates)
+ queryClient.invalidateQueries({ queryKey: ['contacts'] })
+ return redirect(`/contacts/${params.contactId}`)
+ }
export default function Edit() {
- const contact = useLoaderData();
- const navigate = useNavigate();
+ const contact = useLoaderData()
+ const navigate = useNavigate()
return (
- );
+ )
}
diff --git a/examples/react/react-router/src/routes/index.jsx b/examples/react/react-router/src/routes/index.jsx
index 163f2c7de1..5ebb2312c2 100644
--- a/examples/react/react-router/src/routes/index.jsx
+++ b/examples/react/react-router/src/routes/index.jsx
@@ -1,18 +1,18 @@
-import * as React from "react";
+import * as React from 'react'
export default function Index() {
return (
This is a demo for integrating React Router with React Query.
- Check out{" "}
+ Check out{' '}
the docs at reactrouter.com
- and{" "}
+ and{' '}
the docs at tanstack.com
.
- );
+ )
}
diff --git a/examples/react/react-router/src/routes/root.jsx b/examples/react/react-router/src/routes/root.jsx
index 0ced904091..1fab17f85d 100644
--- a/examples/react/react-router/src/routes/root.jsx
+++ b/examples/react/react-router/src/routes/root.jsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import * as React from 'react'
import {
Outlet,
useLoaderData,
@@ -6,42 +6,42 @@ import {
NavLink,
useNavigation,
useSubmit,
-} from "react-router-dom";
-import { useDebounce } from "rooks";
+} from 'react-router-dom'
+import { useDebounce } from 'rooks'
-import { createContact, getContacts } from "../contacts";
-import { useQuery, useIsFetching } from "@tanstack/react-query";
+import { createContact, getContacts } from '../contacts'
+import { useQuery, useIsFetching } from '@tanstack/react-query'
const contactListQuery = (q) => ({
- queryKey: ["contacts", "list", q ?? "all"],
+ queryKey: ['contacts', 'list', q ?? 'all'],
queryFn: () => getContacts(q),
-});
+})
export const loader =
(queryClient) =>
async ({ request }) => {
- const url = new URL(request.url);
- const q = url.searchParams.get("q");
+ const url = new URL(request.url)
+ const q = url.searchParams.get('q')
if (!queryClient.getQueryData(contactListQuery(q).queryKey)) {
- await queryClient.fetchQuery(contactListQuery(q));
+ await queryClient.fetchQuery(contactListQuery(q))
}
- return { q };
- };
+ return { q }
+ }
export const action = (queryClient) => async () => {
- const contact = await createContact();
- queryClient.invalidateQueries({ queryKey: ["contacts", "list"] });
- return contact;
-};
+ const contact = await createContact()
+ queryClient.invalidateQueries({ queryKey: ['contacts', 'list'] })
+ return contact
+}
export default function Root() {
- const { q } = useLoaderData();
- const { data: contacts } = useQuery(contactListQuery(q));
- const searching = useIsFetching({ queryKey: ["contacts", "list"] }) > 0;
- const navigation = useNavigation();
- const submit = useSubmit();
+ const { q } = useLoaderData()
+ const { data: contacts } = useQuery(contactListQuery(q))
+ const searching = useIsFetching({ queryKey: ['contacts', 'list'] }) > 0
+ const navigation = useNavigation()
+ const submit = useSubmit()
- const debouncedSubmit = useDebounce(submit, 500);
+ const debouncedSubmit = useDebounce(submit, 500)
return (
<>
@@ -58,9 +58,9 @@ export default function Root() {
key={q}
autoFocus
defaultValue={q}
- className={searching ? "loading" : ""}
+ className={searching ? 'loading' : ''}
onChange={(event) => {
- debouncedSubmit(event.currentTarget.form);
+ debouncedSubmit(event.currentTarget.form)
}}
/>
@@ -78,7 +78,7 @@ export default function Root() {
- isActive ? "active" : isPending ? "pending" : ""
+ isActive ? 'active' : isPending ? 'pending' : ''
}
>
{contact.first || contact.last ? (
@@ -87,7 +87,7 @@ export default function Root() {
>
) : (
No Name
- )}{" "}
+ )}{' '}
{contact.favorite && ★ }
@@ -102,10 +102,10 @@ export default function Root() {
>
- );
+ )
}
diff --git a/examples/react/rick-morty/.prettierrc b/examples/react/rick-morty/.prettierrc
deleted file mode 100644
index 0967ef424b..0000000000
--- a/examples/react/rick-morty/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/examples/react/rick-morty/src/App.jsx b/examples/react/rick-morty/src/App.jsx
index 1df8647669..044d7cd145 100644
--- a/examples/react/rick-morty/src/App.jsx
+++ b/examples/react/rick-morty/src/App.jsx
@@ -1,15 +1,15 @@
-import React from "react";
-import { BrowserRouter as Router } from "react-router-dom";
-import { ThemeProvider } from "@mui/material";
-import { createMuiTheme } from "@mui/material/styles";
+import React from 'react'
+import { BrowserRouter as Router } from 'react-router-dom'
+import { ThemeProvider } from '@mui/material'
+import { createMuiTheme } from '@mui/material/styles'
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
-import "./styles.css";
-import Layout from "./Layout";
+import './styles.css'
+import Layout from './Layout'
-const queryClient = new QueryClient();
+const queryClient = new QueryClient()
export default function App() {
return (
@@ -21,28 +21,28 @@ export default function App() {
- );
+ )
}
const theme = createMuiTheme({
typography: {
h1: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
h2: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
h3: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
h4: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
h5: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
h6: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
},
-});
+})
diff --git a/examples/react/rick-morty/src/Character.jsx b/examples/react/rick-morty/src/Character.jsx
index 242dd83f22..965e8d2a97 100644
--- a/examples/react/rick-morty/src/Character.jsx
+++ b/examples/react/rick-morty/src/Character.jsx
@@ -1,4 +1,4 @@
-import React from "react";
+import React from 'react'
import {
Typography,
Link,
@@ -9,29 +9,29 @@ import {
TableHead,
TableRow,
Paper,
-} from "@mui/material";
-import { useParams, Link as RouterLink } from "react-router-dom";
-import { useQuery } from "@tanstack/react-query";
-import fetch from "./fetch";
+} from '@mui/material'
+import { useParams, Link as RouterLink } from 'react-router-dom'
+import { useQuery } from '@tanstack/react-query'
+import fetch from './fetch'
function Character() {
- const { characterId } = useParams();
+ const { characterId } = useParams()
const { status, data } = useQuery({
- queryKey: ["character", characterId],
+ queryKey: ['character', characterId],
queryFn: () =>
fetch(`https://rickandmortyapi.com/api/character/${characterId}`),
- });
+ })
- if (status === "pending") return Loading...
;
- if (status === "error") return Error :(
;
+ if (status === 'pending') return Loading...
+ if (status === 'error') return Error :(
- const locationUrlPars = data.location.url.split("/").filter(Boolean);
- const locationId = locationUrlPars[locationUrlPars.length - 1];
+ const locationUrlPars = data.location.url.split('/').filter(Boolean)
+ const locationId = locationUrlPars[locationUrlPars.length - 1]
return (
{data.name}
-
+
@@ -68,23 +68,23 @@ function Character() {
Episodes
{data.episode.map((episode) => {
- const episodeUrlParts = episode.split("/").filter(Boolean);
- const episodeId = episodeUrlParts[episodeUrlParts.length - 1];
+ const episodeUrlParts = episode.split('/').filter(Boolean)
+ const episodeId = episodeUrlParts[episodeUrlParts.length - 1]
- return ;
+ return
})}
- );
+ )
}
function Episode({ id }) {
const { data, status } = useQuery({
- queryKey: ["episode", id],
+ queryKey: ['episode', id],
queryFn: () => fetch(`https://rickandmortyapi.com/api/episode/${id}`),
- });
+ })
- if (status !== "success") {
- return null;
+ if (status !== 'success') {
+ return null
}
return (
@@ -95,23 +95,23 @@ function Episode({ id }) {
- );
+ )
}
function Location({ id }) {
const { data, status } = useQuery({
- queryKey: ["location", id],
+ queryKey: ['location', id],
queryFn: () => fetch(`https://rickandmortyapi.com/api/location/${id}`),
- });
+ })
- if (status === "pending") return Loading...
;
- if (status === "error") return Error :(
;
+ if (status === 'pending') return Loading...
+ if (status === 'error') return Error :(
return (
<>
{data.name} - {data.type}
>
- );
+ )
}
-export default Character;
+export default Character
diff --git a/examples/react/rick-morty/src/Characters.jsx b/examples/react/rick-morty/src/Characters.jsx
index 5995c38b0c..ea3b543000 100644
--- a/examples/react/rick-morty/src/Characters.jsx
+++ b/examples/react/rick-morty/src/Characters.jsx
@@ -1,34 +1,34 @@
-import React from "react";
-import { Typography, Link } from "@mui/material";
-import { Link as RouterLink } from "react-router-dom";
-import { useQuery } from "@tanstack/react-query";
-import fetch from "./fetch";
+import React from 'react'
+import { Typography, Link } from '@mui/material'
+import { Link as RouterLink } from 'react-router-dom'
+import { useQuery } from '@tanstack/react-query'
+import fetch from './fetch'
export default function Characters() {
const { status, data } = useQuery({
- queryKey: ["characters"],
- queryFn: () => fetch("https://rickandmortyapi.com/api/character/"),
- });
+ queryKey: ['characters'],
+ queryFn: () => fetch('https://rickandmortyapi.com/api/character/'),
+ })
- if (status === "pending") return Loading...
;
- if (status === "error") return Error :(
;
+ if (status === 'pending') return Loading...
+ if (status === 'error') return Error :(
- console.info(data);
+ console.info(data)
return (
Characters
{data.results.map((person) => {
return (
-
+
{person.name} - {person.gender}: {person.species}
- );
+ )
})}
- );
+ )
}
diff --git a/examples/react/rick-morty/src/Episode.jsx b/examples/react/rick-morty/src/Episode.jsx
index 2319bbc807..3e66a0cc08 100644
--- a/examples/react/rick-morty/src/Episode.jsx
+++ b/examples/react/rick-morty/src/Episode.jsx
@@ -1,19 +1,19 @@
-import React from "react";
-import { Typography, Link } from "@mui/material";
-import { useParams, Link as RouterLink } from "react-router-dom";
-import { useQuery } from "@tanstack/react-query";
-import fetch from "./fetch";
+import React from 'react'
+import { Typography, Link } from '@mui/material'
+import { useParams, Link as RouterLink } from 'react-router-dom'
+import { useQuery } from '@tanstack/react-query'
+import fetch from './fetch'
function Episode() {
- const { episodeId } = useParams();
+ const { episodeId } = useParams()
const { data, status } = useQuery({
- queryKey: ["episode", episodeId],
+ queryKey: ['episode', episodeId],
queryFn: () =>
fetch(`https://rickandmortyapi.com/api/episode/${episodeId}`),
- });
+ })
- if (status === "pending") return Loading...
;
- if (status === "error") return Error :(
;
+ if (status === 'pending') return Loading...
+ if (status === 'error') return Error :(
return (
@@ -22,22 +22,22 @@ function Episode() {
Characters
{data.characters.map((character) => {
- const characterUrlParts = character.split("/").filter(Boolean);
- const characterId = characterUrlParts[characterUrlParts.length - 1];
- return ;
+ const characterUrlParts = character.split('/').filter(Boolean)
+ const characterId = characterUrlParts[characterUrlParts.length - 1]
+ return
})}
- );
+ )
}
function Character({ id }) {
const { data, status } = useQuery({
- queryKey: ["character", id],
+ queryKey: ['character', id],
queryFn: () => fetch(`https://rickandmortyapi.com/api/character/${id}`),
- });
+ })
- if (status === "pending") return Loading...
;
- if (status === "error") return Error :(
;
+ if (status === 'pending') return Loading...
+ if (status === 'error') return Error :(
return (
@@ -45,7 +45,7 @@ function Character({ id }) {
{data.name}
- );
+ )
}
-export default Episode;
+export default Episode
diff --git a/examples/react/rick-morty/src/Episodes.jsx b/examples/react/rick-morty/src/Episodes.jsx
index db1a4d0812..9b8f692436 100644
--- a/examples/react/rick-morty/src/Episodes.jsx
+++ b/examples/react/rick-morty/src/Episodes.jsx
@@ -1,20 +1,20 @@
-import React from "react";
-import { Typography, Link } from "@mui/material";
-import { Link as RouterLink } from "react-router-dom";
-import { useQuery } from "@tanstack/react-query";
-import fetch from "./fetch";
+import React from 'react'
+import { Typography, Link } from '@mui/material'
+import { Link as RouterLink } from 'react-router-dom'
+import { useQuery } from '@tanstack/react-query'
+import fetch from './fetch'
export default function Episodes() {
const { data, status } = useQuery({
- queryKey: ["episodes"],
- queryFn: () => fetch("https://rickandmortyapi.com/api/episode"),
- });
+ queryKey: ['episodes'],
+ queryFn: () => fetch('https://rickandmortyapi.com/api/episode'),
+ })
- if (status === "pending") {
- return Loading...
;
+ if (status === 'pending') {
+ return Loading...
}
- if (status === "error") {
- return Error :(
;
+ if (status === 'error') {
+ return Error :(
}
return (
@@ -30,5 +30,5 @@ export default function Episodes() {
))}
- );
+ )
}
diff --git a/examples/react/rick-morty/src/Home.jsx b/examples/react/rick-morty/src/Home.jsx
index 5f87ca15f6..3661e86060 100644
--- a/examples/react/rick-morty/src/Home.jsx
+++ b/examples/react/rick-morty/src/Home.jsx
@@ -1,11 +1,11 @@
-import React from "react";
-import { Typography } from "@mui/material";
-import { makeStyles } from "@mui/styles";
-import { Link } from "@mui/material";
-import { Link as RouterLink } from "react-router-dom";
+import React from 'react'
+import { Typography } from '@mui/material'
+import { makeStyles } from '@mui/styles'
+import { Link } from '@mui/material'
+import { Link as RouterLink } from 'react-router-dom'
export default function Home() {
- const classes = useStyles();
+ const classes = useStyles()
return (
@@ -26,16 +26,16 @@ export default function Home() {
tag them as observable.
- Simply associate a key with your fetch call and let{" "}
+ Simply associate a key with your fetch call and let{' '}
React Query handle the rest.
Ready to get started?
- Check out the{" "}
+ Check out the{' '}
Episodes
- {" "}
- and{" "}
+ {' '}
+ and{' '}
Characters
@@ -43,14 +43,14 @@ export default function Home() {
- );
+ )
}
const useStyles = makeStyles(() => ({
main: {
- margin: "44px 0",
- "& p": {
- margin: "12px 0 24px",
+ margin: '44px 0',
+ '& p': {
+ margin: '12px 0 24px',
},
},
-}));
+}))
diff --git a/examples/react/rick-morty/src/Layout.jsx b/examples/react/rick-morty/src/Layout.jsx
index f83953f473..b33a76a9d3 100644
--- a/examples/react/rick-morty/src/Layout.jsx
+++ b/examples/react/rick-morty/src/Layout.jsx
@@ -1,15 +1,15 @@
-import React from "react";
-import Episodes from "./Episodes";
-import Episode from "./Episode";
-import Characters from "./Characters";
-import Character from "./Character";
-import Home from "./Home";
-import { Link, Button } from "@mui/material";
-import { makeStyles } from "@mui/styles";
-import { Routes, Route, Link as RouterLink } from "react-router-dom";
+import React from 'react'
+import Episodes from './Episodes'
+import Episode from './Episode'
+import Characters from './Characters'
+import Character from './Character'
+import Home from './Home'
+import { Link, Button } from '@mui/material'
+import { makeStyles } from '@mui/styles'
+import { Routes, Route, Link as RouterLink } from 'react-router-dom'
export default function Layout() {
- const classes = useStyles();
+ const classes = useStyles()
return (
@@ -38,21 +38,21 @@ export default function Layout() {
- );
+ )
}
const useStyles = makeStyles((theme) => ({
main: {
- margin: "0 auto",
- padding: "16px",
+ margin: '0 auto',
+ padding: '16px',
},
menu: {
- margin: "0 auto",
- display: "flex",
- justifyContent: "center",
- backgroundColor: "#CCC",
- "& button": {
+ margin: '0 auto',
+ display: 'flex',
+ justifyContent: 'center',
+ backgroundColor: '#CCC',
+ '& button': {
margin: theme.spacing(1),
},
},
-}));
+}))
diff --git a/examples/react/rick-morty/src/fetch.jsx b/examples/react/rick-morty/src/fetch.jsx
index a34e54669d..6a1fe60ab5 100644
--- a/examples/react/rick-morty/src/fetch.jsx
+++ b/examples/react/rick-morty/src/fetch.jsx
@@ -1,4 +1,4 @@
export default async function (...args) {
- const res = await fetch(...args);
- return await res.json();
+ const res = await fetch(...args)
+ return await res.json()
}
diff --git a/examples/react/rick-morty/src/index.jsx b/examples/react/rick-morty/src/index.jsx
index bb0b9407de..03066f37fc 100644
--- a/examples/react/rick-morty/src/index.jsx
+++ b/examples/react/rick-morty/src/index.jsx
@@ -1,7 +1,7 @@
-import React from "react";
-import ReactDOM from "react-dom/client";
+import React from 'react'
+import ReactDOM from 'react-dom/client'
-import App from "./App";
+import App from './App'
-const rootElement = document.getElementById("root");
-ReactDOM.createRoot(rootElement).render( );
+const rootElement = document.getElementById('root')
+ReactDOM.createRoot(rootElement).render( )
diff --git a/examples/react/simple/.prettierrc b/examples/react/simple/.prettierrc
deleted file mode 100644
index 0967ef424b..0000000000
--- a/examples/react/simple/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/examples/react/simple/package.json b/examples/react/simple/package.json
index 0e798cc19e..73ec3a4239 100644
--- a/examples/react/simple/package.json
+++ b/examples/react/simple/package.json
@@ -8,11 +8,11 @@
"preview": "vite preview"
},
"dependencies": {
+ "@tanstack/react-query": "^5.0.0-alpha.38",
+ "@tanstack/react-query-devtools": "^5.0.0-alpha.38",
"axios": "^1.4.0",
"react": "^18.2.0",
- "react-dom": "^18.2.0",
- "@tanstack/react-query": "^5.0.0-alpha.38",
- "@tanstack/react-query-devtools": "^5.0.0-alpha.38"
+ "react-dom": "^18.2.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.0.0",
diff --git a/examples/react/simple/src/index.jsx b/examples/react/simple/src/index.jsx
index 2c47ea6dd2..5aa4579fe7 100644
--- a/examples/react/simple/src/index.jsx
+++ b/examples/react/simple/src/index.jsx
@@ -1,49 +1,49 @@
/* eslint-disable jsx-a11y/anchor-is-valid */
-import React from "react";
-import ReactDOM from "react-dom/client";
+import React from 'react'
+import ReactDOM from 'react-dom/client'
import {
QueryClient,
QueryClientProvider,
useQuery,
-} from "@tanstack/react-query";
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
-import axios from "axios";
+} from '@tanstack/react-query'
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
+import axios from 'axios'
-const queryClient = new QueryClient();
+const queryClient = new QueryClient()
export default function App() {
return (
- );
+ )
}
function Example() {
const { isPending, error, data, isFetching } = useQuery({
- queryKey: ["repoData"],
+ queryKey: ['repoData'],
queryFn: () =>
axios
- .get("https://api.github.com/repos/tannerlinsley/react-query")
+ .get('https://api.github.com/repos/tannerlinsley/react-query')
.then((res) => res.data),
- });
+ })
- if (isPending) return "Loading...";
+ if (isPending) return 'Loading...'
- if (error) return "An error has occurred: " + error.message;
+ if (error) return 'An error has occurred: ' + error.message
return (
{data.name}
{data.description}
-
👀 {data.subscribers_count} {" "}
-
✨ {data.stargazers_count} {" "}
+
👀 {data.subscribers_count} {' '}
+
✨ {data.stargazers_count} {' '}
🍴 {data.forks_count}
-
{isFetching ? "Updating..." : ""}
+
{isFetching ? 'Updating...' : ''}
- );
+ )
}
-const rootElement = document.getElementById("root");
-ReactDOM.createRoot(rootElement).render( );
+const rootElement = document.getElementById('root')
+ReactDOM.createRoot(rootElement).render( )
diff --git a/examples/react/star-wars/.prettierrc b/examples/react/star-wars/.prettierrc
deleted file mode 100644
index 0967ef424b..0000000000
--- a/examples/react/star-wars/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/examples/react/star-wars/src/App.jsx b/examples/react/star-wars/src/App.jsx
index 939c5697ae..3ec768ad97 100644
--- a/examples/react/star-wars/src/App.jsx
+++ b/examples/react/star-wars/src/App.jsx
@@ -1,15 +1,15 @@
-import React from "react";
-import { BrowserRouter as Router } from "react-router-dom";
-import { ThemeProvider } from "@mui/material";
-import { createTheme } from "@mui/material/styles";
+import React from 'react'
+import { BrowserRouter as Router } from 'react-router-dom'
+import { ThemeProvider } from '@mui/material'
+import { createTheme } from '@mui/material/styles'
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
-import "./styles.css";
-import Layout from "./Layout";
+import './styles.css'
+import Layout from './Layout'
-const queryClient = new QueryClient();
+const queryClient = new QueryClient()
export default function App() {
return (
@@ -21,28 +21,28 @@ export default function App() {
- );
+ )
}
const theme = createTheme({
typography: {
h1: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
h2: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
h3: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
h4: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
h5: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
h6: {
- fontFamily: "Roboto Mono, monospace",
+ fontFamily: 'Roboto Mono, monospace',
},
},
-});
+})
diff --git a/examples/react/star-wars/src/Character.jsx b/examples/react/star-wars/src/Character.jsx
index ac87562ed1..2797ae36c9 100644
--- a/examples/react/star-wars/src/Character.jsx
+++ b/examples/react/star-wars/src/Character.jsx
@@ -1,4 +1,4 @@
-import React from "react";
+import React from 'react'
import {
Typography,
Link,
@@ -9,33 +9,33 @@ import {
TableHead,
TableRow,
Paper,
-} from "@mui/material";
-import { useParams, Link as RouterLink } from "react-router-dom";
-import { useQuery } from "@tanstack/react-query";
-import fetch from "./fetch";
+} from '@mui/material'
+import { useParams, Link as RouterLink } from 'react-router-dom'
+import { useQuery } from '@tanstack/react-query'
+import fetch from './fetch'
function Character() {
- let params = useParams();
- const characterId = params.characterId;
+ let params = useParams()
+ const characterId = params.characterId
const { status, error, data } = useQuery({
- queryKey: ["character", characterId],
+ queryKey: ['character', characterId],
queryFn: () => fetch(`https://swapi.dev/api/people/${characterId}/`),
- });
+ })
- if (status === "pending") return Loading...
;
- if (status === "error") return Error :(
;
+ if (status === 'pending') return Loading...
+ if (status === 'error') return Error :(
- console.info({ data, status, error });
- const homeworldUrlParts = data.homeworld.split("/").filter(Boolean);
- const homeworldId = homeworldUrlParts[homeworldUrlParts.length - 1];
+ console.info({ data, status, error })
+ const homeworldUrlParts = data.homeworld.split('/').filter(Boolean)
+ const homeworldId = homeworldUrlParts[homeworldUrlParts.length - 1]
- if (status !== "success") {
- return null;
+ if (status !== 'success') {
+ return null
}
return (
{data.name}
-
+
@@ -76,23 +76,23 @@ function Character() {
Films
{data.films.map((film) => {
- const filmUrlParts = film.split("/").filter(Boolean);
- const filmId = filmUrlParts[filmUrlParts.length - 1];
- return ;
+ const filmUrlParts = film.split('/').filter(Boolean)
+ const filmId = filmUrlParts[filmUrlParts.length - 1]
+ return
})}
- );
+ )
}
function Film(props) {
- const { id } = props;
+ const { id } = props
const { data, status } = useQuery({
- queryKey: ["film", id],
+ queryKey: ['film', id],
queryFn: () => fetch(`https://swapi.dev/api/films/${id}/`),
- });
+ })
- if (status !== "success") {
- return null;
+ if (status !== 'success') {
+ return null
}
return (
@@ -102,21 +102,21 @@ function Film(props) {
- );
+ )
}
function Homeworld(props) {
- const { id } = props;
+ const { id } = props
const { data, status } = useQuery({
- queryKey: ["homeworld", id],
+ queryKey: ['homeworld', id],
queryFn: () => fetch(`https://swapi.dev/api/planets/${id}/`),
- });
+ })
- if (status !== "success") {
- return null;
+ if (status !== 'success') {
+ return null
}
- return data.name;
+ return data.name
}
-export default Character;
+export default Character
diff --git a/examples/react/star-wars/src/Characters.jsx b/examples/react/star-wars/src/Characters.jsx
index 8c0e0a29bc..f66d82a1c5 100644
--- a/examples/react/star-wars/src/Characters.jsx
+++ b/examples/react/star-wars/src/Characters.jsx
@@ -1,32 +1,32 @@
-import React from "react";
-import { Typography, Link } from "@mui/material";
-import { Link as RouterLink } from "react-router-dom";
-import { useQuery } from "@tanstack/react-query";
-import fetch from "./fetch";
+import React from 'react'
+import { Typography, Link } from '@mui/material'
+import { Link as RouterLink } from 'react-router-dom'
+import { useQuery } from '@tanstack/react-query'
+import fetch from './fetch'
export default function Characters(props) {
const { status, error, data } = useQuery({
- queryKey: ["characters"],
+ queryKey: ['characters'],
queryFn: () => fetch(`https://swapi.dev/api/people/`),
- });
+ })
- if (status === "pending") return Loading...
;
- if (status === "error") return Error :(
;
+ if (status === 'pending') return Loading...
+ if (status === 'error') return Error :(
return (
Characters
{data.results.map((person) => {
- const personUrlParts = person.url.split("/").filter(Boolean);
- const personId = personUrlParts[personUrlParts.length - 1];
+ const personUrlParts = person.url.split('/').filter(Boolean)
+ const personId = personUrlParts[personUrlParts.length - 1]
return (
-
+
{person.name}
- );
+ )
})}
- );
+ )
}
diff --git a/examples/react/star-wars/src/Film.jsx b/examples/react/star-wars/src/Film.jsx
index faf127b45b..e09426bf3d 100644
--- a/examples/react/star-wars/src/Film.jsx
+++ b/examples/react/star-wars/src/Film.jsx
@@ -1,24 +1,24 @@
-import React from "react";
-import { Typography, Link } from "@mui/material";
-import { useParams, Link as RouterLink } from "react-router-dom";
-import { useQuery } from "@tanstack/react-query";
-import fetch from "./fetch";
+import React from 'react'
+import { Typography, Link } from '@mui/material'
+import { useParams, Link as RouterLink } from 'react-router-dom'
+import { useQuery } from '@tanstack/react-query'
+import fetch from './fetch'
function Film() {
- let params = useParams();
- const filmId = params.filmId;
+ let params = useParams()
+ const filmId = params.filmId
const { data, status, error } = useQuery({
- queryKey: ["film", filmId],
+ queryKey: ['film', filmId],
queryFn: () => fetch(`https://swapi.dev/api/films/${filmId}/`),
- });
+ })
- if (status === "pending") return Loading...
;
+ if (status === 'pending') return Loading...
// this will not be necessary when v1 is released.
if (data == null) {
- console.info("this shouldn't happen but it does 2");
- return Loading...
;
+ console.info("this shouldn't happen but it does 2")
+ return Loading...
}
- if (status === "error") return Error :(
;
+ if (status === 'error') return Error :(
return (
{data.title}
@@ -26,23 +26,23 @@ function Film() {
Characters
{data.characters.map((character) => {
- const characterUrlParts = character.split("/").filter(Boolean);
- const characterId = characterUrlParts[characterUrlParts.length - 1];
- return ;
+ const characterUrlParts = character.split('/').filter(Boolean)
+ const characterId = characterUrlParts[characterUrlParts.length - 1]
+ return
})}
- );
+ )
}
function Character(props) {
- const { id } = props;
+ const { id } = props
const { data, status, error } = useQuery({
- queryKey: ["character", id],
+ queryKey: ['character', id],
queryFn: () => fetch(`https://swapi.dev/api/people/${props.id}/`),
- });
+ })
- if (status !== "success") {
- return null;
+ if (status !== 'success') {
+ return null
}
return (
@@ -51,7 +51,7 @@ function Character(props) {
{data.name}
- );
+ )
}
-export default Film;
+export default Film
diff --git a/examples/react/star-wars/src/Films.jsx b/examples/react/star-wars/src/Films.jsx
index 859772f851..19e13cc851 100644
--- a/examples/react/star-wars/src/Films.jsx
+++ b/examples/react/star-wars/src/Films.jsx
@@ -1,41 +1,41 @@
-import React from "react";
-import { Typography, Link } from "@mui/material";
-import { Link as RouterLink } from "react-router-dom";
-import { useQuery } from "@tanstack/react-query";
-import fetch from "./fetch";
+import React from 'react'
+import { Typography, Link } from '@mui/material'
+import { Link as RouterLink } from 'react-router-dom'
+import { useQuery } from '@tanstack/react-query'
+import fetch from './fetch'
export default function Films(props) {
const { data, status, error } = useQuery({
- queryKey: ["films"],
- queryFn: () => fetch("https://swapi.dev/api/films/"),
- });
+ queryKey: ['films'],
+ queryFn: () => fetch('https://swapi.dev/api/films/'),
+ })
- if (status === "pending") {
- return Loading...
;
+ if (status === 'pending') {
+ return Loading...
}
- if (status === "error") {
- return Error :(
;
+ if (status === 'error') {
+ return Error :(
}
return (
Films
{data.results.map((film) => {
- const filmUrlParts = film.url.split("/").filter(Boolean);
- const filmId = filmUrlParts[filmUrlParts.length - 1];
+ const filmUrlParts = film.url.split('/').filter(Boolean)
+ const filmId = filmUrlParts[filmUrlParts.length - 1]
return (
- {film.episode_id}. {film.title}{" "}
+ {film.episode_id}. {film.title}{' '}
({new Date(Date.parse(film.release_date)).getFullYear()})
- );
+ )
})}
- );
+ )
}
diff --git a/examples/react/star-wars/src/Home.jsx b/examples/react/star-wars/src/Home.jsx
index 27ac0a1678..d78810c4d3 100644
--- a/examples/react/star-wars/src/Home.jsx
+++ b/examples/react/star-wars/src/Home.jsx
@@ -1,11 +1,11 @@
-import React from "react";
-import { Typography } from "@mui/material";
-import { makeStyles } from "@mui/styles";
-import { Link } from "@mui/material";
-import { Link as RouterLink } from "react-router-dom";
+import React from 'react'
+import { Typography } from '@mui/material'
+import { makeStyles } from '@mui/styles'
+import { Link } from '@mui/material'
+import { Link as RouterLink } from 'react-router-dom'
export default function Home(props) {
- const classes = useStyles();
+ const classes = useStyles()
return (
@@ -27,16 +27,16 @@ export default function Home(props) {
tag them as observable.
- Simply associate a key with your fetch call and let{" "}
+ Simply associate a key with your fetch call and let{' '}
React Query handle the rest.
Ready to get started?
- Check out the{" "}
+ Check out the{' '}
Films
- {" "}
- and{" "}
+ {' '}
+ and{' '}
Characters
@@ -44,14 +44,14 @@ export default function Home(props) {
- );
+ )
}
const useStyles = makeStyles((theme) => ({
main: {
- margin: "44px 0",
- "& p": {
- margin: "12px 0 24px",
+ margin: '44px 0',
+ '& p': {
+ margin: '12px 0 24px',
},
},
-}));
+}))
diff --git a/examples/react/star-wars/src/Layout.jsx b/examples/react/star-wars/src/Layout.jsx
index 603c4963c6..eeca6342dd 100644
--- a/examples/react/star-wars/src/Layout.jsx
+++ b/examples/react/star-wars/src/Layout.jsx
@@ -1,15 +1,15 @@
-import React from "react";
-import Films from "./Films";
-import Film from "./Film";
-import Characters from "./Characters";
-import Character from "./Character";
-import Home from "./Home";
-import { Link, Button } from "@mui/material";
-import { makeStyles } from "@mui/styles";
-import { Routes, Route, Link as RouterLink } from "react-router-dom";
+import React from 'react'
+import Films from './Films'
+import Film from './Film'
+import Characters from './Characters'
+import Character from './Character'
+import Home from './Home'
+import { Link, Button } from '@mui/material'
+import { makeStyles } from '@mui/styles'
+import { Routes, Route, Link as RouterLink } from 'react-router-dom'
export default function Layout(props) {
- const classes = useStyles();
+ const classes = useStyles()
return (
@@ -38,21 +38,21 @@ export default function Layout(props) {
- );
+ )
}
const useStyles = makeStyles((theme) => ({
main: {
- margin: "0 auto",
- padding: "16px",
+ margin: '0 auto',
+ padding: '16px',
},
menu: {
- margin: "0 auto",
- display: "flex",
- justifyContent: "center",
- backgroundColor: "#CCC",
- "& button": {
+ margin: '0 auto',
+ display: 'flex',
+ justifyContent: 'center',
+ backgroundColor: '#CCC',
+ '& button': {
margin: theme.spacing(1),
},
},
-}));
+}))
diff --git a/examples/react/star-wars/src/fetch.jsx b/examples/react/star-wars/src/fetch.jsx
index a34e54669d..6a1fe60ab5 100644
--- a/examples/react/star-wars/src/fetch.jsx
+++ b/examples/react/star-wars/src/fetch.jsx
@@ -1,4 +1,4 @@
export default async function (...args) {
- const res = await fetch(...args);
- return await res.json();
+ const res = await fetch(...args)
+ return await res.json()
}
diff --git a/examples/react/star-wars/src/index.jsx b/examples/react/star-wars/src/index.jsx
index bb0b9407de..03066f37fc 100644
--- a/examples/react/star-wars/src/index.jsx
+++ b/examples/react/star-wars/src/index.jsx
@@ -1,7 +1,7 @@
-import React from "react";
-import ReactDOM from "react-dom/client";
+import React from 'react'
+import ReactDOM from 'react-dom/client'
-import App from "./App";
+import App from './App'
-const rootElement = document.getElementById("root");
-ReactDOM.createRoot(rootElement).render( );
+const rootElement = document.getElementById('root')
+ReactDOM.createRoot(rootElement).render( )
diff --git a/examples/react/suspense/.prettierrc b/examples/react/suspense/.prettierrc
deleted file mode 100644
index 9e26dfeeb6..0000000000
--- a/examples/react/suspense/.prettierrc
+++ /dev/null
@@ -1 +0,0 @@
-{}
\ No newline at end of file
diff --git a/examples/react/suspense/src/components/Button.jsx b/examples/react/suspense/src/components/Button.jsx
index e1ba338687..67f33c4bde 100644
--- a/examples/react/suspense/src/components/Button.jsx
+++ b/examples/react/suspense/src/components/Button.jsx
@@ -1,15 +1,15 @@
-import React from "react";
+import React from 'react'
-import Spinner from "./Spinner";
+import Spinner from './Spinner'
export default function Button({ children, onClick }) {
- const [isPending, startTransition] = React.useTransition();
+ const [isPending, startTransition] = React.useTransition()
const handleClick = (e) => {
startTransition(() => {
- onClick(e);
- });
- };
+ onClick(e)
+ })
+ }
return (
<>
@@ -17,5 +17,5 @@ export default function Button({ children, onClick }) {
{children} {isPending ? : null}
>
- );
+ )
}
diff --git a/examples/react/suspense/src/components/Project.jsx b/examples/react/suspense/src/components/Project.jsx
index df75c92890..798d09b3fc 100644
--- a/examples/react/suspense/src/components/Project.jsx
+++ b/examples/react/suspense/src/components/Project.jsx
@@ -1,16 +1,16 @@
-import React from "react";
-import { useQuery } from "@tanstack/react-query";
+import React from 'react'
+import { useQuery } from '@tanstack/react-query'
-import Button from "./Button";
-import Spinner from "./Spinner";
+import Button from './Button'
+import Spinner from './Spinner'
-import { fetchProject } from "../queries";
+import { fetchProject } from '../queries'
export default function Project({ activeProject, setActiveProject }) {
const { data, isFetching } = useQuery({
- queryKey: ["project", activeProject],
+ queryKey: ['project', activeProject],
queryFn: () => fetchProject(activeProject),
- });
+ })
return (
@@ -28,5 +28,5 @@ export default function Project({ activeProject, setActiveProject }) {
- );
+ )
}
diff --git a/examples/react/suspense/src/components/Projects.jsx b/examples/react/suspense/src/components/Projects.jsx
index 9988279309..fad6598aa8 100644
--- a/examples/react/suspense/src/components/Projects.jsx
+++ b/examples/react/suspense/src/components/Projects.jsx
@@ -1,17 +1,17 @@
-import React from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
+import React from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
-import Button from "./Button";
-import Spinner from "./Spinner";
+import Button from './Button'
+import Spinner from './Spinner'
-import { fetchProjects, fetchProject } from "../queries";
+import { fetchProjects, fetchProject } from '../queries'
export default function Projects({ setActiveProject }) {
- const queryClient = useQueryClient();
+ const queryClient = useQueryClient()
const { data, isFetching } = useQuery({
- queryKey: ["projects"],
+ queryKey: ['projects'],
queryFn: fetchProjects,
- });
+ })
return (
@@ -22,17 +22,17 @@ export default function Projects({ setActiveProject }) {
onClick={() => {
// Prefetch the project query
queryClient.prefetchQuery({
- queryKey: ["project", project.name],
+ queryKey: ['project', project.name],
queryFn: () => fetchProject(project.name),
- });
- setActiveProject(project.name);
+ })
+ setActiveProject(project.name)
}}
>
Load
- {" "}
+ {' '}
{project.name}
))}
- );
+ )
}
diff --git a/examples/react/suspense/src/components/Spinner.jsx b/examples/react/suspense/src/components/Spinner.jsx
index f8d7ef9c08..c68cb061ab 100644
--- a/examples/react/suspense/src/components/Spinner.jsx
+++ b/examples/react/suspense/src/components/Spinner.jsx
@@ -1,4 +1,4 @@
-import React from "react";
+import React from 'react'
export default function Spinner() {
return (
@@ -6,8 +6,8 @@ export default function Spinner() {
className="fa fa-circle-o-notch fa-spin"
style={{
marginLeft: 4,
- fontSize: "small",
+ fontSize: 'small',
}}
/>
- );
+ )
}
diff --git a/examples/react/suspense/src/index.jsx b/examples/react/suspense/src/index.jsx
index e1a71fc4ec..1b3622836b 100755
--- a/examples/react/suspense/src/index.jsx
+++ b/examples/react/suspense/src/index.jsx
@@ -1,20 +1,20 @@
-import React, { lazy } from "react";
-import ReactDOM from "react-dom/client";
+import React, { lazy } from 'react'
+import ReactDOM from 'react-dom/client'
import {
useQueryClient,
QueryClient,
QueryClientProvider,
QueryErrorResetBoundary,
-} from "@tanstack/react-query";
-import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
-import { ErrorBoundary } from "react-error-boundary";
+} from '@tanstack/react-query'
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
+import { ErrorBoundary } from 'react-error-boundary'
-import { fetchProjects } from "./queries";
+import { fetchProjects } from './queries'
-import Button from "./components/Button";
+import Button from './components/Button'
-const Projects = lazy(() => import("./components/Projects"));
-const Project = lazy(() => import("./components/Project"));
+const Projects = lazy(() => import('./components/Projects'))
+const Project = lazy(() => import('./components/Project'))
const queryClient = new QueryClient({
defaultOptions: {
@@ -23,20 +23,20 @@ const queryClient = new QueryClient({
suspense: true,
},
},
-});
+})
function App() {
return (
- );
+ )
}
function Example() {
- const queryClient = useQueryClient();
- const [showProjects, setShowProjects] = React.useState(false);
- const [activeProject, setActiveProject] = React.useState(null);
+ const queryClient = useQueryClient()
+ const [showProjects, setShowProjects] = React.useState(false)
+ const [activeProject, setActiveProject] = React.useState(null)
return (
<>
@@ -45,15 +45,15 @@ function Example() {
setShowProjects((old) => {
if (!old) {
queryClient.prefetchQuery({
- queryKey: ["projects"],
+ queryKey: ['projects'],
queryFn: fetchProjects,
- });
+ })
}
- return !old;
- });
+ return !old
+ })
}}
>
- {showProjects ? "Hide Projects" : "Show Projects"}
+ {showProjects ? 'Hide Projects' : 'Show Projects'}
@@ -63,9 +63,9 @@ function Example() {
(
- There was an error!{" "}
+ There was an error!{' '}
resetErrorBoundary()}>Try again
-
{error.message}
+
{error.message}
)}
onReset={reset}
@@ -87,8 +87,8 @@ function Example() {
>
- );
+ )
}
-const rootElement = document.getElementById("root");
-ReactDOM.createRoot(rootElement).render( );
+const rootElement = document.getElementById('root')
+ReactDOM.createRoot(rootElement).render( )
diff --git a/examples/react/suspense/src/queries.js b/examples/react/suspense/src/queries.js
index c9d6277225..db43b5132c 100644
--- a/examples/react/suspense/src/queries.js
+++ b/examples/react/suspense/src/queries.js
@@ -1,25 +1,25 @@
-import axios from "axios";
+import axios from 'axios'
// let count = 0;
export async function fetchProjects(key) {
- console.info("fetch projects");
+ console.info('fetch projects')
// if (count < 4) {
// count++;
// throw new Error("testing");
// }
let { data } = await axios.get(
- `https://api.github.com/users/tannerlinsley/repos?sort=updated`
- );
- await new Promise((r) => setTimeout(r, 1000));
- return data;
+ `https://api.github.com/users/tannerlinsley/repos?sort=updated`,
+ )
+ await new Promise((r) => setTimeout(r, 1000))
+ return data
}
export async function fetchProject(id) {
- console.info("fetch project id", id);
+ console.info('fetch project id', id)
let { data } = await axios.get(
- `https://api.github.com/repos/tannerlinsley/${id}`
- );
- await new Promise((r) => setTimeout(r, 1000));
- return data;
+ `https://api.github.com/repos/tannerlinsley/${id}`,
+ )
+ await new Promise((r) => setTimeout(r, 1000))
+ return data
}
diff --git a/examples/solid/solid-start-streaming/package.json b/examples/solid/solid-start-streaming/package.json
index 7fb073312d..a39a2d6091 100644
--- a/examples/solid/solid-start-streaming/package.json
+++ b/examples/solid/solid-start-streaming/package.json
@@ -6,14 +6,6 @@
"start": "solid-start start"
},
"type": "module",
- "devDependencies": {
- "@types/node": "^18.13.0",
- "esbuild": "^0.14.54",
- "postcss": "^8.4.23",
- "solid-start-node": "^0.2.0",
- "typescript": "^5.0.4",
- "vite": "^4.1.4"
- },
"dependencies": {
"@tanstack/solid-query": "^5.0.0-alpha.38",
"@solidjs/meta": "^0.28.2",
@@ -22,6 +14,14 @@
"solid-start": "^0.2.23",
"undici": "^5.22.1"
},
+ "devDependencies": {
+ "@types/node": "^18.13.0",
+ "esbuild": "^0.14.54",
+ "postcss": "^8.4.23",
+ "solid-start-node": "^0.2.0",
+ "typescript": "^5.0.4",
+ "vite": "^4.1.4"
+ },
"engines": {
"node": ">=16.8"
}
diff --git a/examples/vue/nuxt3/package.json b/examples/vue/nuxt3/package.json
index 0b32bc7320..ca389b3d8d 100644
--- a/examples/vue/nuxt3/package.json
+++ b/examples/vue/nuxt3/package.json
@@ -5,10 +5,10 @@
"build": "nuxi build",
"start": "node .output/server/index.mjs"
},
- "devDependencies": {
- "nuxt": "^3.0.0-rc.12"
- },
"dependencies": {
"@tanstack/vue-query": "^5.0.0-alpha.38"
+ },
+ "devDependencies": {
+ "nuxt": "^3.5.2"
}
}
diff --git a/nx.json b/nx.json
index 6db8ea72b7..fd730deef1 100644
--- a/nx.json
+++ b/nx.json
@@ -52,7 +52,8 @@
"targetDefaults": {
"test:lib": {
"outputs": ["{projectRoot}/coverage"],
- "inputs": ["default", "^public"]
+ "inputs": ["default", "^public"],
+ "dependsOn": ["^build"]
},
"test:eslint": {
"inputs": ["default", "^public"],
diff --git a/packages/query-devtools/package.json b/packages/query-devtools/package.json
index 532915ba90..6c74a04521 100644
--- a/packages/query-devtools/package.json
+++ b/packages/query-devtools/package.json
@@ -49,9 +49,5 @@
"devDependencies": {
"@tanstack/query-core": "^5.0.0-alpha.43",
"vite-plugin-solid": "^2.5.0"
- },
- "peerDependencies": {
- "@tanstack/query-core": "^5.0.0-alpha.43"
- },
- "peerDependenciesMeta": {}
+ }
}
diff --git a/packages/query-devtools/vitest.config.ts b/packages/query-devtools/vitest.config.ts
index 2798c38f41..4955b6b7be 100644
--- a/packages/query-devtools/vitest.config.ts
+++ b/packages/query-devtools/vitest.config.ts
@@ -1,4 +1,3 @@
-import { resolve } from 'path'
import solid from 'vite-plugin-solid'
import { defineConfig } from 'vitest/config'
@@ -12,10 +11,5 @@ export default defineConfig({
globals: true,
coverage: { provider: 'istanbul' },
},
- resolve: {
- alias: {
- '@tanstack/query-core': resolve(__dirname, '..', 'query-core', 'src'),
- },
- },
plugins: [solid()],
})
diff --git a/packages/query-persist-client-core/vitest.config.ts b/packages/query-persist-client-core/vitest.config.ts
index 8b12fe66b1..c37bd3b146 100644
--- a/packages/query-persist-client-core/vitest.config.ts
+++ b/packages/query-persist-client-core/vitest.config.ts
@@ -1,4 +1,3 @@
-import { resolve } from 'path'
import { defineConfig } from 'vitest/config'
export default defineConfig({
@@ -9,9 +8,4 @@ export default defineConfig({
globals: true,
coverage: { provider: 'istanbul' },
},
- resolve: {
- alias: {
- '@tanstack/query-core': resolve(__dirname, '..', 'query-core', 'src'),
- },
- },
})
diff --git a/packages/query-sync-storage-persister/vitest.config.ts b/packages/query-sync-storage-persister/vitest.config.ts
index 6d7d9460c3..221cf1e34e 100644
--- a/packages/query-sync-storage-persister/vitest.config.ts
+++ b/packages/query-sync-storage-persister/vitest.config.ts
@@ -1,4 +1,3 @@
-import { resolve } from 'path'
import { defineConfig } from 'vitest/config'
export default defineConfig({
@@ -9,15 +8,4 @@ export default defineConfig({
globals: true,
coverage: { provider: 'istanbul' },
},
- resolve: {
- alias: {
- '@tanstack/query-core': resolve(__dirname, '..', 'query-core', 'src'),
- '@tanstack/query-persist-client-core': resolve(
- __dirname,
- '..',
- 'query-persist-client-core',
- 'src',
- ),
- },
- },
})
diff --git a/packages/react-query-devtools/package.json b/packages/react-query-devtools/package.json
index b4d70ba203..458835c0c7 100644
--- a/packages/react-query-devtools/package.json
+++ b/packages/react-query-devtools/package.json
@@ -45,7 +45,10 @@
"test:lib:dev": "pnpm run test:lib --watch",
"build": "pnpm build:rollup && pnpm build:types",
"build:rollup": "rollup --config rollup.config.mjs",
- "build:types": "tsc --emitDeclarationOnly && cpy build/lib/index.d.ts build/lib/index.prod.d.ts"
+ "build:types": "tsc --emitDeclarationOnly && cpy index.d.ts index.prod.d.ts --cwd=build/lib"
+ },
+ "dependencies": {
+ "@tanstack/query-devtools": "^5.0.0-alpha.43"
},
"devDependencies": {
"@tanstack/react-query": "^5.0.0-alpha.43",
@@ -55,9 +58,6 @@
"react-dom": "^18.2.0",
"react-error-boundary": "^3.1.4"
},
- "dependencies": {
- "@tanstack/query-devtools": "^5.0.0-alpha.43"
- },
"peerDependencies": {
"@tanstack/react-query": "^5.0.0-alpha.43",
"react": "^18.0.0",
diff --git a/packages/react-query-devtools/test-setup.ts b/packages/react-query-devtools/test-setup.ts
index 4bc5d7f0d3..e184eb4e20 100644
--- a/packages/react-query-devtools/test-setup.ts
+++ b/packages/react-query-devtools/test-setup.ts
@@ -1,5 +1,5 @@
import { act } from '@testing-library/react'
-import { notifyManager } from '@tanstack/query-core'
+import { notifyManager } from '@tanstack/react-query'
// Wrap notifications with act to make sure React knows about React Query updates
notifyManager.setNotifyFunction((fn) => {
diff --git a/packages/react-query-devtools/vitest.config.ts b/packages/react-query-devtools/vitest.config.ts
index c461200db0..70eec41e33 100644
--- a/packages/react-query-devtools/vitest.config.ts
+++ b/packages/react-query-devtools/vitest.config.ts
@@ -1,4 +1,3 @@
-import { resolve } from 'path'
import { defineConfig } from 'vitest/config'
export default defineConfig({
@@ -11,16 +10,4 @@ export default defineConfig({
globals: true,
coverage: { provider: 'istanbul' },
},
- resolve: {
- alias: {
- '@tanstack/query-core': resolve(__dirname, '..', 'query-core', 'src'),
- '@tanstack/react-query': resolve(__dirname, '..', 'react-query', 'src'),
- '@tanstack/query-persist-client-core': resolve(
- __dirname,
- '..',
- 'query-persist-client-core',
- 'src',
- ),
- },
- },
})
diff --git a/packages/react-query-persist-client/package.json b/packages/react-query-persist-client/package.json
index 1ea3a86aec..72845ed115 100644
--- a/packages/react-query-persist-client/package.json
+++ b/packages/react-query-persist-client/package.json
@@ -37,17 +37,16 @@
"build:rollup": "rollup --config rollup.config.mjs",
"build:types": "tsc --emitDeclarationOnly"
},
+ "dependencies": {
+ "@tanstack/query-persist-client-core": "^5.0.0-alpha.43"
+ },
"devDependencies": {
- "@tanstack/query-core": "^5.0.0-alpha.43",
"@tanstack/react-query": "^5.0.0-alpha.43",
"@types/react": "^18.2.4",
"@types/react-dom": "^18.2.4",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
- "dependencies": {
- "@tanstack/query-persist-client-core": "^5.0.0-alpha.43"
- },
"peerDependencies": {
"@tanstack/react-query": "^5.0.0-alpha.43"
}
diff --git a/packages/react-query-persist-client/src/__tests__/utils.ts b/packages/react-query-persist-client/src/__tests__/utils.ts
index 8667303dc6..9bc45a3945 100644
--- a/packages/react-query-persist-client/src/__tests__/utils.ts
+++ b/packages/react-query-persist-client/src/__tests__/utils.ts
@@ -1,7 +1,7 @@
import { act } from '@testing-library/react'
-import type { QueryClientConfig } from '@tanstack/query-core'
-import { QueryClient } from '@tanstack/query-core'
+import type { QueryClientConfig } from '@tanstack/react-query'
+import { QueryClient } from '@tanstack/react-query'
export function createQueryClient(config?: QueryClientConfig): QueryClient {
return new QueryClient(config)
diff --git a/packages/react-query-persist-client/vitest.config.ts b/packages/react-query-persist-client/vitest.config.ts
index c461200db0..70eec41e33 100644
--- a/packages/react-query-persist-client/vitest.config.ts
+++ b/packages/react-query-persist-client/vitest.config.ts
@@ -1,4 +1,3 @@
-import { resolve } from 'path'
import { defineConfig } from 'vitest/config'
export default defineConfig({
@@ -11,16 +10,4 @@ export default defineConfig({
globals: true,
coverage: { provider: 'istanbul' },
},
- resolve: {
- alias: {
- '@tanstack/query-core': resolve(__dirname, '..', 'query-core', 'src'),
- '@tanstack/react-query': resolve(__dirname, '..', 'react-query', 'src'),
- '@tanstack/query-persist-client-core': resolve(
- __dirname,
- '..',
- 'query-persist-client-core',
- 'src',
- ),
- },
- },
})
diff --git a/packages/react-query/package.json b/packages/react-query/package.json
index a4dcf871b2..c1af073973 100644
--- a/packages/react-query/package.json
+++ b/packages/react-query/package.json
@@ -42,6 +42,9 @@
"!build/codemods/**/__testfixtures__",
"!build/codemods/**/__tests__"
],
+ "dependencies": {
+ "@tanstack/query-core": "^5.0.0-alpha.43"
+ },
"devDependencies": {
"@types/react": "^18.2.4",
"@types/react-dom": "^18.2.4",
@@ -49,9 +52,6 @@
"react-dom": "^18.2.0",
"react-error-boundary": "^3.1.4"
},
- "dependencies": {
- "@tanstack/query-core": "^5.0.0-alpha.43"
- },
"peerDependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
diff --git a/packages/react-query/vitest.config.ts b/packages/react-query/vitest.config.ts
index 30946ff816..e31d0611cf 100644
--- a/packages/react-query/vitest.config.ts
+++ b/packages/react-query/vitest.config.ts
@@ -1,4 +1,3 @@
-import { resolve } from 'path'
import { defineConfig } from 'vitest/config'
export default defineConfig({
@@ -11,9 +10,4 @@ export default defineConfig({
globals: true,
coverage: { provider: 'istanbul' },
},
- resolve: {
- alias: {
- '@tanstack/query-core': resolve(__dirname, '..', 'query-core', 'src'),
- },
- },
})
diff --git a/packages/solid-query/package.json b/packages/solid-query/package.json
index f5080227b3..a98dc546ac 100644
--- a/packages/solid-query/package.json
+++ b/packages/solid-query/package.json
@@ -57,6 +57,5 @@
},
"peerDependencies": {
"solid-js": "^1.6.13"
- },
- "peerDependenciesMeta": {}
+ }
}
diff --git a/packages/solid-query/vitest.config.ts b/packages/solid-query/vitest.config.ts
index 2798c38f41..4955b6b7be 100644
--- a/packages/solid-query/vitest.config.ts
+++ b/packages/solid-query/vitest.config.ts
@@ -1,4 +1,3 @@
-import { resolve } from 'path'
import solid from 'vite-plugin-solid'
import { defineConfig } from 'vitest/config'
@@ -12,10 +11,5 @@ export default defineConfig({
globals: true,
coverage: { provider: 'istanbul' },
},
- resolve: {
- alias: {
- '@tanstack/query-core': resolve(__dirname, '..', 'query-core', 'src'),
- },
- },
plugins: [solid()],
})
diff --git a/packages/svelte-query-devtools/package.json b/packages/svelte-query-devtools/package.json
index d3f76ffe9e..19699d341a 100644
--- a/packages/svelte-query-devtools/package.json
+++ b/packages/svelte-query-devtools/package.json
@@ -33,23 +33,21 @@
"test:eslint": "eslint --ext .svelte,.ts ./src",
"build": "svelte-package --input ./src --output ./build/lib"
},
+ "dependencies": {
+ "@tanstack/query-devtools": "^5.0.0-alpha.43",
+ "esm-env": "^1.0.0"
+ },
"devDependencies": {
"@sveltejs/package": "^2.0.2",
"@sveltejs/vite-plugin-svelte": "^2.4.0",
- "@testing-library/svelte": "^3.2.2",
+ "@tanstack/svelte-query": "^5.0.0-alpha.43",
"eslint-plugin-svelte": "^2.29.0",
- "jsdom": "^22.0.0",
"svelte": "^3.54.0",
"svelte-check": "^3.4.3",
"tslib": "^2.5.2",
"typescript": "^5.0.4",
"vite": "^4.2.0"
},
- "dependencies": {
- "@tanstack/query-devtools": "^5.0.0-alpha.43",
- "@tanstack/svelte-query": "^5.0.0-alpha.43",
- "esm-env": "^1.0.0"
- },
"peerDependencies": {
"@tanstack/svelte-query": "^5.0.0-alpha.43",
"svelte": "^3.54.0"
diff --git a/packages/svelte-query-devtools/vite.config.ts b/packages/svelte-query-devtools/vite.config.ts
index 2779794d9b..8ad4e192c8 100644
--- a/packages/svelte-query-devtools/vite.config.ts
+++ b/packages/svelte-query-devtools/vite.config.ts
@@ -1,19 +1,6 @@
-import { resolve } from 'node:path'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [svelte()],
- resolve: {
- alias: {
- '@tanstack/query-core': resolve(__dirname, '..', 'query-core', 'src'),
- '@tanstack/query-devtools': resolve(
- __dirname,
- '..',
- 'query-devtools',
- 'src',
- ),
- '@tanstack/svelte-query': resolve(__dirname, '..', 'svelte-query', 'src'),
- },
- },
})
diff --git a/packages/svelte-query/package.json b/packages/svelte-query/package.json
index 97451d6f50..124feb7742 100644
--- a/packages/svelte-query/package.json
+++ b/packages/svelte-query/package.json
@@ -37,6 +37,9 @@
"test:lib:dev": "pnpm run test:lib --watch",
"build": "svelte-package --input ./src --output ./build/lib"
},
+ "dependencies": {
+ "@tanstack/query-core": "^5.0.0-alpha.43"
+ },
"devDependencies": {
"@sveltejs/package": "^2.0.2",
"@sveltejs/vite-plugin-svelte": "^2.4.0",
@@ -49,9 +52,6 @@
"typescript": "^5.0.4",
"vite": "^4.2.0"
},
- "dependencies": {
- "@tanstack/query-core": "^5.0.0-alpha.43"
- },
"peerDependencies": {
"svelte": "^3.54.0"
}
diff --git a/packages/svelte-query/vite.config.ts b/packages/svelte-query/vite.config.ts
index fa3e88c238..ea042a0513 100644
--- a/packages/svelte-query/vite.config.ts
+++ b/packages/svelte-query/vite.config.ts
@@ -1,14 +1,8 @@
-import { resolve } from 'node:path'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [svelte()],
- resolve: {
- alias: {
- '@tanstack/query-core': resolve(__dirname, '..', 'query-core', 'src'),
- },
- },
test: {
name: 'svelte-query',
watch: false,
diff --git a/packages/vue-query/vitest.config.ts b/packages/vue-query/vitest.config.ts
index 2f512d54a9..77e3122c40 100644
--- a/packages/vue-query/vitest.config.ts
+++ b/packages/vue-query/vitest.config.ts
@@ -1,4 +1,3 @@
-import { resolve } from 'path'
import { defineConfig } from 'vitest/config'
export default defineConfig({
@@ -11,9 +10,4 @@ export default defineConfig({
setupFiles: ['test-setup.ts'],
coverage: { provider: 'istanbul' },
},
- resolve: {
- alias: {
- '@tanstack/query-core': resolve(__dirname, '..', 'query-core', 'src'),
- },
- },
})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index bbfb0d4f98..bd836f46c5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -213,6 +213,12 @@ importers:
algoliasearch:
specifier: 4.17.1
version: 4.17.1
+ react:
+ specifier: ^18.2.0
+ version: 18.2.0
+ react-dom:
+ specifier: ^18.2.0
+ version: 18.2.0(react@18.2.0)
devDependencies:
'@tanstack/eslint-plugin-query':
specifier: ^5.0.0-alpha.36
@@ -226,12 +232,6 @@ importers:
'@vitejs/plugin-react':
specifier: ^4.0.0
version: 4.0.0(vite@4.2.1)
- react:
- specifier: ^18.2.0
- version: 18.2.0
- react-dom:
- specifier: ^18.2.0
- version: 18.2.0(react@18.2.0)
typescript:
specifier: ^5.0.4
version: 5.0.4
@@ -1473,9 +1473,6 @@ importers:
specifier: ^5.0.0-alpha.43
version: link:../query-persist-client-core
devDependencies:
- '@tanstack/query-core':
- specifier: ^5.0.0-alpha.43
- version: link:../query-core
'@tanstack/react-query':
specifier: ^5.0.0-alpha.43
version: link:../react-query
@@ -1547,9 +1544,6 @@ importers:
'@tanstack/query-devtools':
specifier: ^5.0.0-alpha.43
version: link:../query-devtools
- '@tanstack/svelte-query':
- specifier: ^5.0.0-alpha.43
- version: link:../svelte-query
esm-env:
specifier: ^1.0.0
version: 1.0.0
@@ -1560,15 +1554,12 @@ importers:
'@sveltejs/vite-plugin-svelte':
specifier: ^2.4.0
version: 2.4.0(svelte@3.55.0)(vite@4.2.1)
- '@testing-library/svelte':
- specifier: ^3.2.2
- version: 3.2.2(svelte@3.55.0)
+ '@tanstack/svelte-query':
+ specifier: ^5.0.0-alpha.43
+ version: link:../svelte-query
eslint-plugin-svelte:
specifier: ^2.29.0
version: 2.29.0(eslint@8.34.0)(svelte@3.55.0)
- jsdom:
- specifier: ^22.0.0
- version: 22.0.0
svelte:
specifier: ^3.54.0
version: 3.55.0