Skip to content

Commit 3353301

Browse files
committed
Mutation
1 parent 1cbd2ae commit 3353301

File tree

3 files changed

+46
-6
lines changed

3 files changed

+46
-6
lines changed

src/App.tsx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
import "./App.css";
2-
import PostList from "./react-query/PostList";
2+
import TodoForm from "./react-query/TodoForm";
33
import TodoList from "./react-query/TodoList";
44

5+
56
function App() {
6-
return <PostList />;
7+
return (
8+
<>
9+
<TodoForm />
10+
<TodoList />
11+
</>
12+
)
713
}
814

915
export default App;

src/react-query/TodoForm.tsx

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,51 @@
1+
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
12
import { useRef } from 'react';
3+
import { Todo } from './hooks/useTodos';
4+
import axios from 'axios';
25

36
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 || [])]);
518

19+
if(ref.current) ref.current.value = '';
20+
}
21+
});
22+
const ref = useRef<HTMLInputElement>(null);
623
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+
}}>
839
<div className="col">
940
<input ref={ref} type="text" className="form-control" />
1041
</div>
1142
<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>
1346
</div>
1447
</form>
48+
</>
1549
);
1650
};
1751

src/react-query/hooks/useTodos.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { useQuery } from "@tanstack/react-query";
22
import axios from "axios";
33

4-
interface Todo {
4+
export interface Todo {
55
id: number;
66
title: string;
77
userId: number;

0 commit comments

Comments
 (0)