({
editingIndex,
setEditingIndex,
}: {
editingIndex: number
setEditingIndex: React.Dispatch<React.SetStateAction<number | null>>
})
| 231 | } |
| 232 | |
| 233 | function 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> |
nothing calls this directly
no test coverage detected
searching dependent graphs…