Skip to content

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

Description

@bharatsewani1993

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions