简体   繁体   中英

Only fetch the data if user press search or Enter in React?

I've set up a search Bar to fetch the data from the backend and return it.

CODE:

const App = () => {

const[datas,setDatas] = useState([])   //NOthing to do with this.

const [space,setSpace] = useState(null)
const [print, setPrint] = useState(false)


function getData(val){
  console.log(val.target.value)
  setSpace(val.target.value);
  setPrint(false)
}

console.log(space)  //Returning inputted text in console. Works well

  useEffect(() => {
    const fecthPosts = async () => {
      let initial_url = `http://localhost:4000/search` 
      let url = initial_url + "?text=" + space  
       
       const res = await fetch(url);
       const {result} = await res.json();

     setDatas(result);
    fecthPosts();
  },[space]);

return(
<div className="App">
     {                  //Displaying on search
        print?
         <>
        <h2>{space}</h2>  //submited text
        <div> 
       {results.map((field) => 
       <p>{field.title}</p> 
       <p>{field.author}</p> 
       )}
        </div>
        </>
        :null
      }
   <input type="text" onChange={getData} />
 <button onClick={() => setSpace(true)}>search</button>
</div>
  )
 }
};

export default App;

Now, this code works perfectly fine. But when I click on Network Tab then,

It's fetching data from every text I'm typing. Problems with onChange

search?text=s
search?text=sa  
search?text=sam 
search?text=sams
search?text=samsu   
search?text=samsun
search?text=samsung

I don't want this to be happen because I've got limited No. of requests to send.

Anyone plz help to solve this issue.I've tried several things but nothing working...

NOTE: I can't use Timeout and any other method which works... only search or fetch data if user press enter or click the button .

You can fetch inside a short timeout (say, after 2 seconds of inactivity after typing) with a ref.

Don't ignore possible errors either - unhandled rejections should always be avoided.

const timeoutRef = useRef();
useEffect(() => {
    const doFetch = () => {
        const url = 'http://localhost:4000/search?text=' + space
        fetch(url)
            .then(res => res.json())
            .then(({ result }) => setDatas(result))
            .catch(handleErrors); // don't forget this
    };
    clearTimeout(timeoutRef.current);
    timeoutRef.current = setTimeout(doFetch, 2000);
}, [space]);

I think there are some issues with the code, for example when showing the search result, if I understand correctly:

{results.map((field) => 

should be

{datas.map((field) => 

right?

For your current problem,

  1. You're calling the search API every time when the input text is changed.
  2. Only show the search result when the search button is clicked.

So why not only trigger the API call when the search button is clicked?

您可以使用 denounce,仅在 n 秒后调用搜索 API。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM