Passing function returns without declaring another variable

(jsx code, treat ‘database’ like an array/obj)

<input onChange={e => e.target.value} type='text'/>
<div> {database.filter(data => data.includes( ??? )} </div>

I want to access the return value of my onChange function where the ??? are. A common way to do this would be to create another variable in the state property (if in a React component), save the value of onChange in that variable and then access that variable in data.includes. However, this creates a new, unnecessary variable that only repeats the return value of my function.

state = {
  inputValue = ''
}
<input onChange={e => {inputValue = e.target.value}} type='text'/>
<div> {database.filter(data => data.includes(inputValue)} </div>

is there another way to pass the result of my onChange function to data.includes directly?

Answer

You can’t.

You need the value immediately but the function isn’t going to return a value until it is called. It won’t be called until the user has done something to trigger the change event. This is much, much later than “immediately”.

I still have to create a variable in my state property that I don’t really need since it’s just the return statement of my onHandleChange function,

You do really need that.

The change event handler should store the selection in the state. Changing the state will trigger a rerender. This will update the view with new data.

Leave a Reply

Your email address will not be published. Required fields are marked *