Issue
const { isLoading, isError, data, error, refetch } = useQuery(
"university",
async () => {
const { data } = await axios(
"http://universities.hipolabs.com/search?name=middle"
);
console.log("THis is data", data);
return data;
}
);
And This is the Search Box Where I want to map Data of University name that is typed
<Typeahead
id="basic-example"
onChange={setSelected}
options={university}
placeholder="Choose a School..."
selected={selected}
/>
Solution
This question has been asked so many times that I've added it to my react-query FAQs: https://tkdodo.eu/blog/react-query-fa-qs#how-can-i-pass-parameters-to-refetch
searchValue
needs to be part of the queryKey:
const { isLoading, isError, data, error, refetch } = useQuery(
["university", searchValue],
async () => {
const { data } = await axios(
`http://universities.hipolabs.com/search?name=${searchValue}`
);
console.log("THis is data", data);
return data;
},
);
then, once the user selects a new searchValue, the query will automatically refetch. If searchValue changes on every key stroke, use something like useDebounce to defer the query:
const [searchValue, setSearchValue] = useState('') // value from search input
const name = useDebounce(searchValue, 500)
const { isLoading, isError, data, error, refetch } = useQuery(
["university", name],
async () => {
const { data } = await axios(
`http://universities.hipolabs.com/search?name=${name}`
);
console.log("THis is data", data);
return data;
},
);
Answered By - TkDodo Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.