Asdf1234567
Asdf1234567

Reputation: 550

React: How to properly set state at first load

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?

Upvotes: 0

Views: 251

Answers (2)

Syed SaeedulHassan Ali
Syed SaeedulHassan Ali

Reputation: 594

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);
}

Upvotes: 1

rakeshpatra
rakeshpatra

Reputation: 761

    constructor(props) {
        super(props);

        this.state = {
          customFilter: value
        }
      }

You can define the state in the constructor.

Upvotes: 0

Related Questions