sortinousn
sortinousn

Reputation: 647

How to access a nested function externally in JS/React?

I'm having some trouble with scoping functions. I'm trying to get the value of "item" but I'm getting undefined when I try to access it outside of the function. How can I make "item" accessible from the outside onLinkClicked()? I need to be able to use item in my render.

   onLinkClicked() {

   var parent = this.state.username
       //console.log(this.state.username)
   var conn = new jsforce.Connection({
       serverUrl: 'https://cs63.salesforce.com',
       accessToken: sessionStorage.getItem('token')
   })
   conn.query("SELECT Id, Name, Phone FROM Contact WHERE LastName='" + parent + "'",
       function(err, result) {
           if (err) {
               return console.error(err);
           }

             var a = result
              a.records.forEach(function(item) {
               result = (item.Name + ' ' + item.Phone);

               console.log(item) // I'm trying to get the value of item, which outputs correctly here

           });

       }
   )

   console.log(item) //Here I get undefined due to being out of scope, how can I access item?.

  }

 render () {

return (
    <div className='menubox' id='menubox'>
  <div className='searchbar-container'>
    <form onSubmit={e => e.preventDefault()}>
      <input
        type='text'
        size='25'
        placeholder='Contact Last Name'
        onChange={this.handleChange.bind(this)}
        value={this.state.username} />
        <button
        type='submit'
        onClick={this.onLinkClicked.bind(this)}>
        Search
      </button>
    </form>
   </div>
   <div dangerouslySetInnerHTML={ { __html: item } }>
   </div>
  </div>

 )
}

Upvotes: 1

Views: 419

Answers (1)

user3637541
user3637541

Reputation: 693

Define a global variable where you store your result. If you are using react (the react-class you are using is not entirely shown) you should use this.setState to set a state and use it elsewhere. You can not use item after the conn.query-method as conn.query is asynchronous. If you want to do processing with it that do it in the callback.

I assumed you need item in the render-function. With the state this is easily possible.

Please note that i changed the function-definitions to lambda-expressions (() => {}). This is necessary in order to use this within the callback.

... () {
  // ...
  conn.query("SELECT Id, Name, Phone FROM Contact WHERE LastName='" + parent + "'",
           (err, result) => {
             if (err) {
               return console.error(err);
             }

             var a = result;
             a.records.forEach((item) => {
               result = (item.Name + ' ' + item.Phone);
               this.setState({item : item});
             });

           };
          );

  // You will never be able to get item here, because you are using an
  // asynchronous function. If you want to use item further in this
  // function you have to use it within the callback of conn.query.
  console.log(item);
};

render () {
  // Nevertheless you can use this.state.item here. I assume this is
  // what you want.
  return ( // ...
  );
}

Upvotes: 1

Related Questions