Search code examples
reactjssharepointspfx

returning undefined for the function in spfx react


tried cascading drop down using 2 columns. but it keeps returning undefined. unable to setState in dropdown function

the values are returning in console, but not able to set the state

    private async test(getVal: any):promis<void> {
    ...
    
    var timePeriod = this.dropdown(getval.key);
    log(timePeriod)
    //returns undefined
    }
    
    public dropdown(val: string){
    sp.web.lists.getbytitle("").items.select("").filter("" + val + "'").getAll().the(function (data){
    log(data)
    for(var k in data){
    timePeriod.push({key:data[k].period, text: data[k].Period})
    }
    
    retur data;
    }
    
    )
    }

Solution

  • Your dropdown function is not returning properly. Also, there are several typos in the code snippet you shared.

    You need to create a variable outside your promise handler which would what would be returned after you get the data from the SharePoint API.

    I have updated your code snippet showcasing how you address the issue.

    public dropdown(val: string){
        let output = [];
        sp.web.lists.getbytitle("").items.select("").filter("" + val + "'").getAll().then(function (data){
            //console.log(data);
            for(var k in data){
                output.push({key:data[k].period, text: data[k].Period})
            }
    
            /** 
             * The return statement below doesn't have any effect on the outcome of the function 
             * as any return here is for the internal function of the success/error handler
             *
             *
             * return data;
            */
        } );
        return output;
    }