MCPcopy Index your code
hub / github.com/TanStack/query / EditTodo

Function EditTodo

examples/react/playground/src/index.tsx:233–340  ·  view source on GitHub ↗
({
  editingIndex,
  setEditingIndex,
}: {
  editingIndex: number
  setEditingIndex: React.Dispatch<React.SetStateAction<number | null>>
})

Source from the content-addressed store, hash-verified

231}
232
233function EditTodo({
234 editingIndex,
235 setEditingIndex,
236}: {
237 editingIndex: number
238 setEditingIndex: React.Dispatch<React.SetStateAction<number | null>>
239}) {
240 const queryClient = useQueryClient()
241
242 // Don't attempt to query until editingIndex is truthy
243 const { status, data, isFetching, error, failureCount, refetch } = useQuery({
244 queryKey: ['todo', { id: editingIndex }],
245 queryFn: () => fetchTodoById({ id: editingIndex }),
246 })
247
248 const [todo, setTodo] = React.useState(data || {})
249
250 React.useEffect(() => {
251 if (editingIndex !== null && data) {
252 setTodo(data)
253 } else {
254 setTodo({})
255 }
256 }, [data, editingIndex])
257
258 const saveMutation = useMutation({
259 mutationFn: patchTodo,
260 onSuccess: (data) => {
261 // Update `todos` and the individual todo queries when this mutation succeeds
262 queryClient.invalidateQueries({ queryKey: ['todos'] })
263 queryClient.setQueryData(['todo', { id: editingIndex }], data)
264 },
265 })
266
267 const onSave = () => {
268 saveMutation.mutate(todo)
269 }
270
271 const disableEditSave =
272 status === 'pending' || saveMutation.status === 'pending'
273
274 return (
275 <div>
276 <div>
277 {data ? (
278 <>
279 <button onClick={() => setEditingIndex(null)}>Back</button> Editing
280 Todo "{data.name}" (#
281 {editingIndex})
282 </>
283 ) : null}
284 </div>
285 {status === 'pending' ? (
286 <span>Loading... (Attempt: {failureCount + 1})</span>
287 ) : error ? (
288 <span>
289 Error! <button onClick={() => refetch()}>Retry</button>
290 </span>

Callers

nothing calls this directly

Calls 7

useQueryClientFunction · 0.90
useQueryFunction · 0.90
useMutationFunction · 0.90
fetchTodoByIdFunction · 0.85
refetchFunction · 0.85
invalidateQueriesMethod · 0.45
setQueryDataMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…