0

I am new with @pnp/sp and I am having problems with my code:

public render(): React.ReactElement<IVisualizadorPermisosProps> {
    var arbol=[];
    sp.web.get().then((data)=>{
      arbol.push({name: data.Title, children:[]});
    });

    //Other code

    return (
      <div id="principal">
        <Select options={opciones} onChange={this.onUserSelection} />
        <div id="treeWrapper" style={{ width: '50em', height: '20em' }}>

        <Tree data={arbol} />

        </div>
      </div>
    );
  }

My problem here is that executing this code, the code inside the sp.web.get() block is not executing before the rest of the code, as I pretend. For example the return statement is executing before arbol.push({name: data.Title, children:[]}); so I get execution errors cause variable arbol can't be empty. If I put a break point inside the "get" block, it reaches the break point in the middle of the execution of the other code.

This situation makes me believe that the "get" call is asynchronous.

Is that truth? What is the solution to my problem?

Thanks.

  • 1
    Try calling sp.web.get() in componentDidMount method. – Ganesh Sanap Jul 26 '19 at 11:34
1

Yes get call is asynchrnous, you should not use render method to get data because render method will be called every time react state will changed and it will again call api causing infinite loop. for you case, on high level I think you can use below.

componentDidMount(){
    sp.web.get().then((data)=>{
      var arbol=[];

      arbol.push({name: data.Title, children:[]});
      this.setState({items: arbol});
    });
  }


  public render(): React.ReactElement<IVisualizadorPermisosProps> {


    //Other code

    return (
      <div id="principal">
        <Select options={opciones} onChange={this.onUserSelection} />
        <div id="treeWrapper" style={{ width: '50em', height: '20em' }}>

        <Tree data={items} />

        </div>
      </div>
    );
  }
| improve this answer | |
  • Thank you Siddharth! That make sense and works! – xero399 Jul 26 '19 at 12:46
  • just one more question. What if I have a get call inside a recursive function? I will have the same problem. – xero399 Jul 26 '19 at 12:48
  • 1
    if you are calling rest api inside loop, make sure to wait till all call has response back...set the state once you have consolidated data....so in this case also render method will be only called once. – Siddharth Vaghasia Jul 26 '19 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.