|
| 1 | +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; |
1 | 2 | import { useRef } from 'react';
|
| 3 | +import { Todo } from './hooks/useTodos'; |
| 4 | +import axios from 'axios'; |
2 | 5 |
|
3 | 6 | const TodoForm = () => {
|
4 |
| - const ref = useRef<HTMLInputElement>(null); |
| 7 | + const queryClient = useQueryClient(); |
| 8 | + const addTodo = useMutation<Todo, Error, Todo>({ |
| 9 | + mutationFn: (todo: Todo) => |
| 10 | + axios |
| 11 | + .post<Todo>('https://jsonplaceholder.typicode.com/todos', todo) |
| 12 | + .then(res => res.data), |
| 13 | + onSuccess: (savedTodo, newTodo) => { |
| 14 | + // queryClient.invalidateQueries({ |
| 15 | + // queryKey: ['todos'] |
| 16 | + // }) |
| 17 | + queryClient.setQueryData<Todo[]>(['todos'], todos => [savedTodo, ...(todos || [])]); |
5 | 18 |
|
| 19 | + if(ref.current) ref.current.value = ''; |
| 20 | + } |
| 21 | + }); |
| 22 | + const ref = useRef<HTMLInputElement>(null); |
6 | 23 | return (
|
7 |
| - <form className="row mb-3"> |
| 24 | + <> |
| 25 | + { addTodo.error && <div className="alert alert-danger"> |
| 26 | + {addTodo.error.message} |
| 27 | + </div> } |
| 28 | + <form className="row mb-3" onSubmit={event => { |
| 29 | + event.preventDefault(); |
| 30 | + |
| 31 | + if(ref.current && ref.current.value) |
| 32 | + addTodo.mutate({ |
| 33 | + id: 0, |
| 34 | + title: ref.current?.value, |
| 35 | + completed: false, |
| 36 | + userId: 1 |
| 37 | + }) |
| 38 | + }}> |
8 | 39 | <div className="col">
|
9 | 40 | <input ref={ref} type="text" className="form-control" />
|
10 | 41 | </div>
|
11 | 42 | <div className="col">
|
12 |
| - <button className="btn btn-primary">Add</button> |
| 43 | + <button className="btn btn-primary" disabled={addTodo.isLoading}> |
| 44 | + {addTodo.isLoading ? 'Adding...' : 'Add'} |
| 45 | + </button> |
13 | 46 | </div>
|
14 | 47 | </form>
|
| 48 | + </> |
15 | 49 | );
|
16 | 50 | };
|
17 | 51 |
|
|
0 commit comments