简体   繁体   中英

handling multiple ajax calls in reactjs

I've got the following code in my react component.

componentDidMount() {
    getOrganizationsForUserTemp().then((organizations) => {
        this.setState({
            userOrganizations: organizations,
        });
    });

    getUsersOfOrganizationTemp().then((users) => {
        this.setState({
            userOrganizations: users,
        });
    })
}

The above code initiates two ajax calls and when the response is retrieved, it updates the state of the component which results in a re-render of the component.

My problem is that, when the first response is received, the component renders perfectly and then when the second response comes, the previously rendered components disappear from the DOM. I guess that when the second response updates the state, there is no reference for the previous response state.

How can I manage multiple ajax calls in such a way that I could have multiple in a single component? what am I doing wrong here.

Since you are storing the response of both ajax calls into the same state variable you are facing this issue.

You need to do something like

componentDidMount() {
    getOrganizationsForUserTemp().then((organizations) => {
        this.setState({
            userOrganizations: organizations,
        });
    });

    getUsersOfOrganizationTemp().then((users) => {
        this.setState({
            users: users,
        });
    })
}

organizations & user are stored in separate state variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM