1

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.

2
  • 1
    Since you are storing the response of both ajax calls into the same state variable you are facing this issue. Commented Apr 4, 2018 at 5:24
  • In the first call you are updating userOrganizations: organizations and in the second call you are updating userOrganizations with user? This does not make sense to me. You should probably have another state variable to hold users data and use it to render the HTML. Commented Apr 4, 2018 at 5:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.