Answer the question
In order to leave comments, you need to log in
How to output the results correctly?
Guys, tell me how to correctly display the results obtained through axios?
It is necessary that 5 results are displayed by coincidence. By default, nothing should be displayed
At the moment, when you click on the input and write any one character, all articles from the database are displayed and are not removed when the input
is cleared Now I sketched such a component
export default function Search() {
const [query, setQuery] = useState('')
const [data, setData] = useState({results: []})
useEffect(() => {
const fetchData = async () => {
const result = await axios(
`http://localhost:8000/api/articles/?search=${query}`,
)
setData(result.data)
}
fetchData()
}, [query])
const handleSearch = e => {
e.preventDefault()
if (query) {
Router.push(`/search/${query}`)
}
}
return (
<form onSubmit={handleSearch}>
<input
type='text'
value={query}
onChange={event => setQuery(event.target.value)}
/>
{data.results.map(item => (
<a href={item.slug} key={item.id}>
{item.title}
</a>
))}
</form>
)
}
Answer the question
In order to leave comments, you need to log in
You have query as a dependency in useEffect. Every time the query changes, useEffect fires again and makes a request to the server, which in turn causes the data to be updated.
Try like this:
useEffect(() => {
const fetchData = async () => {
const result = await axios(
`http://localhost:8000/api/articles/?search=${query}`,
)
setData(result.data)
}
if (query) {
fetchData()
}
}, [query])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question