import React from 'react' import ReactDOM from 'react-dom/client' import { QueryClient, QueryClientProvider, useMutation, useQuery, useQueryClient, } from '@tanstack/react-query' import { ReactQueryDevtools } from '@tanstack/react-query-devtools' import './styles.css' let id = 0 let list = [ 'apple', 'banana', 'pineapple', 'grapefruit', 'dragonfruit', 'grapes', ].map((d) => ({ id: id++, name: d, notes: 'These are some notes' })) type Todos = typeof list type Todo = Todos[0] let errorRate = 0.05 let queryTimeMin = 1000 let queryTimeMax = 2000 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) React.useEffect(() => { errorRate = localErrorRate queryTimeMin = localFetchTimeMin queryTimeMax = localFetchTimeMax }, [localErrorRate, localFetchTimeMax, localFetchTimeMin]) React.useEffect(() => { queryClient.setDefaultOptions({ queries: { staleTime, gcTime, }, }) }, [gcTime, staleTime]) return (

The "staleTime" and "gcTime" durations have been altered in this example to show how query stale-ness and query caching work on a granular level

Stale Time:{' '} setStaleTime(parseFloat(e.target.value))} style={{ width: '100px' }} />
Garbage collection Time:{' '} setGcTime(parseFloat(e.target.value))} style={{ width: '100px' }} />

Error Rate:{' '} setErrorRate(parseFloat(e.target.value))} style={{ width: '100px' }} />
Fetch Time Min:{' '} setLocalFetchTimeMin(parseFloat(e.target.value))} style={{ width: '60px' }} />{' '}
Fetch Time Max:{' '} setLocalFetchTimeMax(parseFloat(e.target.value))} style={{ width: '60px' }} />


) } function App() { const queryClient = useQueryClient() const [editingIndex, setEditingIndex] = React.useState(null) const [views, setViews] = React.useState(['', 'fruit', 'grape']) // const [views, setViews] = React.useState([""]); return (


{views.map((view, index) => (
{ setViews((old) => [...old, '']) }} />
))}
{editingIndex !== null ? ( <>
) : null}
) } function Todos({ initialFilter = '', setEditingIndex, }: { initialFilter: string setEditingIndex: React.Dispatch> }) { const [filter, setFilter] = React.useState(initialFilter) const { status, data, isFetching, error, failureCount, refetch } = useQuery({ queryKey: ['todos', { filter }], queryFn: fetchTodos, }) return (
{status === 'pending' ? ( Loading... (Attempt: {failureCount + 1}) ) : status === 'error' ? ( Error: {error.message}
) : ( <>
    {data ? data.map((todo) => (
  • {todo.name}{' '}
  • )) : null}
{isFetching ? ( Background Refreshing... (Attempt: {failureCount + 1}) ) : (   )}
)}
) } function EditTodo({ editingIndex, setEditingIndex, }: { editingIndex: number setEditingIndex: React.Dispatch> }) { const queryClient = useQueryClient() // Don't attempt to query until editingIndex is truthy const { status, data, isFetching, error, failureCount, refetch } = useQuery({ queryKey: ['todo', { id: editingIndex }], queryFn: () => fetchTodoById({ id: editingIndex }), }) const [todo, setTodo] = React.useState(data || {}) React.useEffect(() => { if (editingIndex !== null && data) { setTodo(data) } else { setTodo({}) } }, [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) }, }) const onSave = () => { saveMutation.mutate(todo) } const disableEditSave = status === 'pending' || saveMutation.status === 'pending' return (
{data ? ( <> Editing Todo "{data.name}" (# {editingIndex}) ) : null}
{status === 'pending' ? ( Loading... (Attempt: {failureCount + 1}) ) : error ? ( Error! ) : ( <>
{saveMutation.status === 'pending' ? 'Saving...' : saveMutation.status === 'error' ? saveMutation.error.message : 'Saved!'}
{isFetching ? ( Background Refreshing... (Attempt: {failureCount + 1}) ) : (   )}
)}
) } function AddTodo() { const queryClient = useQueryClient() const [name, setName] = React.useState('') const addMutation = useMutation({ mutationFn: postTodo, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['todos'] }) }, }) return (
setName(e.target.value)} disabled={addMutation.status === 'pending'} />
{addMutation.status === 'pending' ? 'Saving...' : addMutation.status === 'error' ? addMutation.error.message : 'Saved!'}
) } function fetchTodos({ signal, queryKey: [, { filter }] }): Promise { console.info('fetchTodos', { filter }) if (signal) { 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)), ) } resolve(list.filter((d) => d.name.includes(filter))) }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin), ) }) } function fetchTodoById({ id }: { id: number }): Promise { console.info('fetchTodoById', { id }) return new Promise((resolve, reject) => { setTimeout( () => { if (Math.random() < errorRate) { return reject( new Error(JSON.stringify({ fetchTodoById: { id } }, null, 2)), ) } resolve(list.find((d) => d.id === id)) }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin), ) }) } function postTodo({ name, notes }: Omit) { 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)), ) } const todo = { name, notes, id: id++ } list = [...list, todo] resolve(todo) }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin), ) }) } function patchTodo(todo?: Todo): Promise { console.info('patchTodo', todo) return new Promise((resolve, reject) => { setTimeout( () => { if (Math.random() < errorRate) { return reject(new Error(JSON.stringify({ patchTodo: todo }, null, 2))) } list = list.map((d) => { if (d.id === todo.id) { return todo } return d }) resolve(todo) }, queryTimeMin + Math.random() * (queryTimeMax - queryTimeMin), ) }) } const rootElement = document.getElementById('root') as HTMLElement ReactDOM.createRoot(rootElement).render()