rkit / react-select2-wrapper

Wrapper for Select2
MIT License
163 stars 97 forks source link

I want to update react states, after getting data from Ajax response, but it is not working. #97

Open bharatsewani1993 opened 4 years ago

bharatsewani1993 commented 4 years ago

Hi, I am using the select2 Ajax function to get data from an API. and Once I receive data I am trying to process it and want to update my react states. . . to do so, I tried the following way. . componentDidMount(){ window.myGlobalVar.MyProductFunction = (result) => {
const productlist = result.map((result) => { return { id: result.title, text: result.title, } }
);

  this.setState((prevState) => {
    return { 
      products: prevState.products.concat(productlist) 
    };
  });  

  return;
};  

}

and tried to call this global function in the select2 processResults(). It is as following. . . <Select2 name={"one"} data={products} onSelect={(e) => {handleOnChange(e.target.value)}} defaultValue={value} value={value} options={{ placeholder: "Dynamic Product API", dropdownAutoWidth:true, ajax: { type:"GET", url: this.state.endpoint.ajax_url+"getproducts", dataType: 'json', delay: 250, //Process data here processResults: function (data) { window.myGlobalVar.MyProductFunction(data); }, cache: true }
} } />

But this is not passing argument/variable to my global callback function. It starts to execute it and gives the following error. jQuery.Deferred exception: Cannot read property 'results' of undefined TypeError: Cannot read property 'results' of undefined . . Then I also put a condition to check the 'result' . componentDidMount(){ window.rpReactPlugin.callback = (result) => { console.log("Global function calling.");
if(typeof result != "undefined"){ console.log("I am in if part " + result); const productlist = result.map((result) => { return { id: result.title, text: result.title, } }
);

    this.setState((prevState) => {
      return { 
        products: prevState.products.concat(productlist) 
      };
    });  

    return;
  }else{
    console.log("result not defined! else part");
  }  
}

} . even though no luck. My main goal is to change react state with the Ajax Data. . . Is that possible using react-select2-wrapper? If it is possible, please let me know how? . Thank you Bharat