Question

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.

Was it helpful?

Solution

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>
    );
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top