Home > Software design >  React: How to properly set state at first load
React: How to properly set state at first load

Time:08-11

I have this function that gets some initial data in db:

private getFilter() {
    let getResp;
    let defaultselected = [];
    axios.get(getEndPoint)
        .then(response => {
            getResp = response.data;
            defaultselected = JSON.parse(getResp['JsonValue']);
            this.setState({ customFilter: defaultselected});
        })
}

And this function that loads data from db also:

     getOpenClaims = (pageNumber: number) => {
         console.log('getOpenClaims', this.state.customFilter)
//logic here
    }

on first load, this.state.customFilter is undefined but if I getOpenClaims is executed again by other way, this.state.customFilter has already it's expected value and I already validated that getFilter has a return data from console.log

And here is how I called both functions:

async componentDidMount() {
    document.title = "Claim Aging";
    this.getOpenClaims(1);
}

componentWillMount() {
    this.getFilter();
}

What Am I missing here?

CodePudding user response:

You need to wait for execution of getFilter()before calling getOpenClaims

A little refactoring can help

private async getFilter() { // made this function a promise, using async/await
    let getResp;
    let defaultselected = [];
    const response = await axios.get(getEndPoint)
    getResp = response.data;
    defaultselected = JSON.parse(getResp['JsonValue']);
    this.setState({ customFilter: defaultselected});
}

async componentDidMount() {
    document.title = "Claim Aging";
    await this.getFilter(); // wait for promise to resolve and then call `getOpenClaims`
    this.getOpenClaims(1);
}

CodePudding user response:

    constructor(props) {
        super(props);

        this.state = {
          customFilter: value
        }
      }

You can define the state in the constructor.

  • Related