Ad

How To Export A Function From A Class, So To Be Able To Import It Into Another Class To Use

- 1 answer

To be clear, I am learning TypeScript and React for spfx developments. I have read and taken part in tutorials and other answers on various sources and Stack Overflow and haven't found them enough to help me.

Here is my function in the EvalReqNewForm class (getGrades()):

export default class EvalReqNewForm extends React.Component<IEvalReqNewProps, IEvalReqNewState> {
    constructor(props){
        super(props);
        this.state = {
            EvalType: null,
            JobTitReportTo: null,
            JobTitReportToNum: null,
            PropGradeList: [],
            SelectedGrade: undefined,
            CompPos: null,
            ContextNewJobCode: null
        };
        this._onJobTitReportToChange = this._onJobTitReportToChange.bind(this);
        this._onJobTitReportToNumChange = this._onJobTitReportToNumChange.bind(this);
        this._onPropGradeChange = this._onPropGradeChange.bind(this);

    }

...

public _getGrades() {
        pnp.sp.web.lists.getByTitle("Grades").items.get().then((items: any[]) =>{
          let returnedGrades:IDropdownOption[]= items.map((item) =>{return {key:item.Title, text:item.Title};});
         this.setState({PropGradeList : returnedGrades});
        });
      }

And I want to use the _getGrades() function from the other class to use in a ComponentDidMount() in order to the 'Grades' from the SP list.

Does it involve using props? Or can the function be simply exported and imported into the class where I want to use it?

Please understand I'm learning the basics here!

Ad

Answer

TL;DR

Create a function that only depends on it's parameters and export/import it.


Or can the function be simply exported and imported into the class where I want to use it?

What you can do is create a function that depends only on it's parameters.

So it would be something like

export function getGrades(something){
    // do what ever you want with something
    return somethingYouDid
}

And then you import it to other files and use it like

import { getGrades } from '...'

...

public _getGrades() {
    const results = getGrades(someDataFromSomeWhere)
    this.setState({PropGradeList : results});        
}

I also see that you are using promises, so maybe you will need to use async/await in your case.

Edit:

As said in the comments

I can't seem to use export within a class

You should use it out side of the class, you will have to functions. One out side of the class that have all the logic and other inside that class that only calls the outside function.

export function getGrades(something){
    // do what ever you want with something
    return somethingYouDid
}

class ... {

    ...

    public _getGrades() {
        const results = getGrades(someDataFromSomeWhere)
        this.setState({PropGradeList : results});        
    }

}
Ad
source: stackoverflow.com
Ad