val studentContainer = FC("StudentsContainer") { _: Props ->
val queryClient = useQueryClient()
val studentListQueryKey = arrayOf("studentList")
.unsafeCast<QueryKey>()
val query = useQuery<String, QueryError, String, QueryKey>(
queryKey = studentListQueryKey,
queryFn = {
fetchText(Config.studentsPath)
}
)
val addStudentMutation =
useMutation<HTTPResult, Any, Student, Any>(
mutationFn = { student: Student ->
fetch(
Config.studentsPath,
jso { method = "POST"
headers = json(
"Content-Type" to "application/json")
body = Json.encodeToString(student) } ) },
options = jso {
onSuccess = { _: Any, _: Any, _: Any? ->
queryClient.invalidateQueries<Any>(studentListQueryKey)
} } )
val deleteStudentMutation =
useMutation<HTTPResult, Any, ItemId, Any>(
mutationFn = { studentId: ItemId ->
fetch(
"${Config.studentsPath}$studentId",
jso { method = "DELETE" }
)
},
options = jso {
onSuccess = { _: Any, _: Any, _: Any? ->
queryClient.invalidateQueries<Any>(studentListQueryKey)
}
}
)
val updateStudentMutation =
useMutation<HTTPResult, Any, Item<Student>, Any>(
mutationFn = { studentItem: Item<Student> ->
fetch(
"${Config.studentsPath}${studentItem.id}",
jso {
method = "PUT"
headers = json(
"Content-Type" to "application/json")
body = Json.encodeToString(studentItem.elem) } ) },
options = jso {
onSuccess = { _: Any, _: Any, _: Any? ->
queryClient.invalidateQueries<Any>(studentListQueryKey)
} } )
val items =
Json.decodeFromString<Array<Item<Student>>>(query.data ?: "")
CAddStudent {
addStudent = { it: Student ->
addStudentMutation.mutateAsync(it, null)
} }
CStudentList {
students = items
deleteStudent = { it: ItemId ->
deleteStudentMutation.mutateAsync(it, null)
}
updateStudent = { it: Item<Student> ->
updateStudentMutation.mutateAsync(it, null)
} }