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
.