PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How Can I implement this API End point for Search Purpose Using React Query?

 October 14, 2022     axios, filtering, javascript, react-query, reactjs     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing