In react, I want to get data from a database. I attempted to get the data from database using getCoor() and put in the constructor method. I defined variable private data:any=[]; and defined a state, this.state={data:[]}
Here I am trying to
Problem: The data from getCoor is not stored in my variables.
componentDidMount() {
this.defaultCoor();
const Markers = async () => {
await this.getCoor(); // this.data=json;
await this.addGoogleMapScript();//do something with this.data
}
Markers();
}
The this.data is empty. I am trying to wait for the getCoor to complete the API call, get the data and pass to addGoogleMapscript, is this possible in React?
Solution
private getCoor() {
const qurl = `/_api/web/lists/getbytitle('${this.props.list}')/items?$select=*&$orderby=Created asc`;
const opt: ISPHttpClientOptions = {
headers: { "Content-Type": "application/json;odata=verbose" }
};
return this.props.spHttpClient
.get(
this.props.context.pageContext.web.absoluteUrl + qurl,
SPHttpClient.configurations.v1,
opt
)
.then((response: SPHttpClientResponse) => {
return response.json().then((json: any) => {
this.setState({ data: json.value });
return (this.data = json);
});
});
}
this.data:any=[]; was defined after the constructors method in the class based React Component Add Return in the API functions and return this.data :)
You are getting the data but not assigning it to a variable. For this to work, your Markers
function should look something like this.
componentDidMount() {
this.defaultCoor();
const Markers = async () => {
const data = await this.getCoor(); // this.data=json;
await this.addGoogleMapScript(data); //do something with this.data
}
Markers();
}