-1

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

  • Get data from database using API calls
  • pass this the data using another API call.

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 :)

Random I.T
  • 121
  • 1
  • 10

1 Answers1

1

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();
}

Manan Joshi
  • 629
  • 1
  • 6
  • 17
  • In my getCoor I have made assignment to the data like this this.data =json; in my addGoogleMapscript I use this.data for something else but I found this .data is undefined. I am suggesting that this.data will be assigned after the componentDidmount finishes ? If that is the case how can I ensure I get this.data before I run the other functions using this.data – Random I.T Mar 25 '20 at 04:46
  • Can you post a complete example? This was a little bit confusing. – Manan Joshi Mar 25 '20 at 05:17
  • Thanks @Mannan it works in my getCoor i forgot to add return return in my API Call – Random I.T Mar 25 '20 at 10:23