Home > Net >  React JS onKeyUp event does not sending data to function
React JS onKeyUp event does not sending data to function

Time:01-18

Im trying to create an ajax user search like linkedin's, so when i type a character from the keyboard i should get results without pressing the enter key.

In my input field i have the onKeyUp={sendData(this)} to send the data in the sendData function, and then fetch the results.

<input type="text" id="userfield" onKeyUp={sendData(this)}/>
 function sendData (input){
    if (input!=null){
    console.log("data:",input)
    fetch('/userSearch',{
      method:'POST',
      headers:{'Content-Type': 'application/json'},
      body: JSON.stringify({ input: input.value})
    
    })
    }
  }

My problem is that in the console.log("data:",input) line i get undefined. Which means the onKeyUp event sends nothing to the function. Im i missing something?

CodePudding user response:

In React onKeyUp and event listeners in general expect a function to be passed, and will pass the event as an argument by default. In your case you want to pass the sendData function like so:

<input type="text" id="userfield" onKeyUp={sendData}/>

and then receive the input element like:

function sendData (event){
   const input = event.target;
   // Do stuff with input
  }

Also if you are trying to fetch some data you have to handle it somehow. You should either add a .then((result)=>{/* Handle the result */}) to the fetch call or make sendData an async function and then await the result like:

async function sendData (event){
   const input = event.target;
   const result = await fetch(/*...*/)
  }

CodePudding user response:

Simply you can use

   <input type="text" id="userfield" onKeyUp={(e)=>sendData(e.target.value)}/>

e.target gives you the element that triggered the event.

e.target.value retrieves the value of that element

  • Related