Skip to content

Commit c176553

Browse files
committed
refactor(search): extract search mutation logic into reusable hook
- Moved search API mutation logic from Search component into dedicated useSearchMutation hook - Improves code reusability and separation of concerns - Enables search functionality to be used across multiple components - Reduces code duplication and improves maintainability
1 parent f43c9b4 commit c176553

2 files changed

Lines changed: 34 additions & 28 deletions

File tree

examples/ts-react-search/src/components/HeroSection/Search/Search.tsx

Lines changed: 3 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,21 @@
11
'use client'
22

33
import { useState } from 'react'
4-
import { useNavigate } from '@tanstack/react-router'
5-
import { useMutation } from '@tanstack/react-query'
64
import QuickPrompts from './QuickPrompts'
75
import SearchForm from './SearchForm'
86
import type { FormEvent } from 'react'
7+
import useSearchMutation from '@/hooks/useSearchMutation.ts'
98

109
function Search() {
11-
const navigate = useNavigate()
1210
const [value, setValue] = useState('')
1311

14-
const { mutate, isPending, error } = useMutation({
15-
mutationFn: async (content: string) => {
16-
const response = await fetch('/api/search', {
17-
method: 'POST',
18-
headers: {
19-
'Content-Type': 'application/json',
20-
},
21-
body: JSON.stringify({ content }),
22-
})
23-
24-
if (!response.ok) {
25-
throw new Error('Search request failed')
26-
}
27-
28-
return response.json()
29-
},
30-
onSuccess: async (json) => {
31-
const { name, parameters } = json?.data ?? {}
32-
33-
if (name && parameters) {
34-
await navigate({ to: `/${name}`, search: parameters })
35-
}
36-
},
37-
})
12+
const { mutate: search, isPending, error } = useSearchMutation()
3813

3914
function handleSubmit(event: FormEvent) {
4015
event.preventDefault()
4116

4217
if (value.trim() && !isPending) {
43-
mutate(value)
18+
search(value)
4419
setValue('')
4520
}
4621
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { useMutation } from '@tanstack/react-query'
2+
import { useNavigate } from '@tanstack/react-router'
3+
4+
function useSearchMutation() {
5+
const navigate = useNavigate()
6+
7+
return useMutation({
8+
mutationFn: async (content: string) => {
9+
const response = await fetch('/api/search', {
10+
method: 'POST',
11+
headers: { 'Content-Type': 'application/json' },
12+
body: JSON.stringify({ content }),
13+
})
14+
15+
if (!response.ok) {
16+
throw new Error('Search request failed')
17+
}
18+
19+
return response.json()
20+
},
21+
onSuccess: async (json) => {
22+
const { name, parameters } = json?.data ?? {}
23+
24+
if (name && parameters) {
25+
await navigate({ to: `/${name}`, search: parameters })
26+
}
27+
},
28+
})
29+
}
30+
31+
export default useSearchMutation

0 commit comments

Comments
 (0)