/
mutationWithRefetch.js
149 lines (140 loc) · 4.09 KB
/
mutationWithRefetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import React, { useState } from "react";
import { nanoid } from "nanoid";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { delay } from "@/lib/delay";
import Link from "next/link";
import { Home } from "@/components/Icons";
import Image from "next/image";
import eli from "../assets/eli.webp";
import { returnPicture } from "@/components/Todo";
async function updateTodo(todo) {
await fetch(`http://localhost:8000/todos/${todo.id}`, {
method: "PUT",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
id: nanoid(),
user: todo.user,
task: todo.task,
done: todo.done,
}),
});
}
function Todo({ todo }) {
const queryClient = useQueryClient();
const changeTodoMutation = useMutation(updateTodo, {
onSettled: () => queryClient.invalidateQueries({ queryKeys: ["todos"] }),
});
function changeTodoStatus(e, id) {
const updatedTodo = { ...todo, done: e.target.checked };
changeTodoMutation.mutate(updatedTodo);
}
const pic = returnPicture(todo.user);
return (
<div className="bg-white text-black rounded-lg grid grid-cols-[auto_1fr_auto] items-center gap-4 py-2 px-4">
<input
type="checkbox"
checked={todo.done}
onChange={(e) => changeTodoStatus(e, todo.id)}
/>
<p>{todo.task}</p>
<Image
src={pic}
alt="profile picture"
className="rounded-full"
height={60}
with={60}
></Image>
</div>
);
}
async function createTodo(todo) {
const response = await fetch("http://localhost:8000/todos", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
id: nanoid(),
user: todo.user,
task: todo.task,
done: false,
}),
});
const result = await response.json();
if (!response.ok) {
throw new Error(result.message);
}
return result;
}
async function fetchTodos() {
await delay(1500);
return fetch("http://localhost:8000/todos").then((res) => res.json());
}
function Mutation() {
const createTodoMutation = useMutation(createTodo, {
onSettled: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
// onSuccess: (data, querydata) => console.log(data, querydata),
});
const queryClient = useQueryClient();
const [todo, setTodo] = useState({ user: "", task: "" });
function changeTodo(e) {
const newObject = {};
newObject[e.target.name] = e.target.value;
setTodo({ ...todo, ...newObject });
}
function onFormSubmit(e) {
e.preventDefault();
createTodoMutation.mutate(todo);
}
const todos = useQuery(["todos"], fetchTodos);
return (
<div className="min-h-screen max-w-5xl m-[auto] py-10 px-4">
<Link href="/">
<Home fill="#fff"></Home>
</Link>
<h1 className="text-4xl font-extrabold tanstack-query-gradient py-2 pb-4">
Mutation with Refetch
</h1>
<form onSubmit={onFormSubmit} className="grid grid-cols-1 gap-4">
<div className="flex gap-4 items-end">
<label htmlFor="user" className="text-xl font-bold">
User:
</label>
<input
type="text"
className="text-black flex-1"
name="user"
id="user"
onChange={changeTodo}
value={todo.user}
/>
</div>
<div className="flex gap-4 items-end">
<label htmlFor="task" className="text-xl font-bold">
Task:
</label>
<input
type="text"
className="text-black flex-1"
name="task"
id="task"
onChange={changeTodo}
value={todo.task}
/>
</div>
<button type="submit" className="justify-self-end">
create todo
</button>
</form>
{todos.isLoading ? <span className="loader"></span> : null}
<div className="grid grid-cols-2 gap-4 pt-8">
{todos.isSuccess
? todos.data.map((todo) => <Todo todo={todo} key={todo.id}></Todo>)
: null}
</div>
</div>
);
}
export default Mutation;