user6579134
user6579134

Reputation: 839

call second function only after first function has been called - react native

I just started with react native and I'm pulling data from an API. The first function calls data successfully and the second function will need a variable from the first function before it can make a successful call. I'm trying to make the second API call successful but it fails

componentDidMount = async () => {
const communities = await API.getUserCommunityInfo(userId);
console.log(communities)
this.setState({userCommunities: communities, communityMemberId: communities[0].member.id, communityId: communities[0].community.id}, 
console.log(this.state),
this.getGroups()
)

}

SECOND FUNCTION

getGroups = async () => {
const groups = await API.getGroups(communityMemberId)
this.setState({userGroups: groups ,showLoader: false})
}

The second function will need a state from the first function communityMemberId before it makes a successful call

Upvotes: 0

Views: 2363

Answers (3)

Mitro
Mitro

Reputation: 278

Just add a property into a second function or add a callback function after setState is finished.

componentDidMount = async () => {
    const communities = await API.getUserCommunityInfo(userId);
    console.log(communities)
    this.setState({
       userCommunities: communities, 
       communityMemberId: communities[0].member.id, 
       communityId: communities[0].community.id
    }, () => {
        this.getGroups(this.state.communityMemberId); // callback function after the state is updated
    });
    // or 
    this.getGroups(communities[0].member.id); // this is faster since user don't wait state to be updated
}

getGroups = async (communityMemberId) => {
    const groups = await API.getGroups(communityMemberId)
    this.setState({userGroups: groups ,showLoader: false})
}

Upvotes: 0

Junius L
Junius L

Reputation: 16122

You were not passing the callback properly. By passing the callback to .setState() the second function will run once the first function finish setting state.

componentDidMount = async () => {
  const communities = await API.getUserCommunityInfo(userId);
  console.log(communities);
  this.setState(
    {
      userCommunities: communities,
      communityMemberId: communities[0].member.id,
      communityId: communities[0].community.id
    },
    () => {
      console.log(this.state);
      this.getGroups()
    }
  );
};

getGroups function

getGroups = async () => {
  const groups = await API.getGroups(this.state.communityMemberId)
  this.setState({userGroups: groups ,showLoader: false})
}

Upvotes: 1

Malik Hezret
Malik Hezret

Reputation: 249

You can check if the first function's response and if it success then call second function.

getGroups = async () => {
const groups = await API.getGroups(communityMemberId)
this.setState({userGroups: groups ,showLoader: false})
   if(succees){
    //call second function
    this.secondFunction()
   }
}

Upvotes: 0

Related Questions