cubefox
cubefox

Reputation: 1301

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?

Upvotes: 0

Views: 60

Answers (2)

Quentin
Quentin

Reputation: 943935

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.

Upvotes: 1

Beginner
Beginner

Reputation: 9125

So in your component you need to hold a state for the input change, then you need to set the state for the each change to the state variable.

Once state is updated react will trigger the re render.

Initially the state variable is null, so once you type in in the input field only you need to check with database variable.

Note : Is database variable is coming from props or state.

I hope you understand , please let me know if you are facing any other issue.

import React , {Component} from 'react'

class App extends Component{

  state ={
   inputCurrentValue: null
  }

   onHandleChange = e => this.setState({
     inputCurrentValue: e.target.value
   })

  render(){
    return(
      <div>
       <input onChange={this.onHandleChange} type='text'/>
       <div>
       {
       this.state.inputCurrentValue ?
        database.filter(data => data.includes(this.state.inputCurrentValue)
        :
        null
       }     
       </div>
      </div>
    )
  }
}

Upvotes: 1

Related Questions