Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
bharatsewani1993 opened this issue Jul 23, 2020 · 0 comments

Comments

@bharatsewani1993
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant