lin
lin

Reputation: 187

How to call fetches sequentially (A -> B -> C) inside a React component?

I have 3 fetch functions: a(), b(a_id), c(b_id). Function a will return an a_id and pass to function b, and b will return an id and pass to c.

componentDidUpdate(prevProps) {
  this.gotoanotherPage(this.props.a_id);
}

generateBody() {
  this.props.a();
  this.props.b(this.props.a_id);
  this.props.c(this.props.b_id);
}

render() {
  body = generateBody();
  return <framework {body}/>
}

My problem is a() has not finished fetching and getting a response back yet, yet b and c already execute and this.props.a_id and this.props.b_id are undefined. I couldn't modify the a,b, and c functions.

Anyone know how to set a function call in an order?

Upvotes: 2

Views: 1006

Answers (1)

GG.
GG.

Reputation: 21844

You can use componentDidMount to call the first fetch, then use componentDidUpdate to call the second fetch that depends on the first one. Then do the same thing for the third fetch.

You can use prevProps to check if you received the first and second responses.

Your component will look to something like this:

class MyComponent extends Component {
  componentDidMount() {
    this.props.fetchA();
  }

  componentDidUpdate(prevProps) {
    if (!prevProps.a_id && this.props.a_id) { // it means you received a_id
      this.props.fetchB(this.props.a_id);
    }

    if (!prevProps.b_id && this.props.b_id) { // it means you received b_id
      this.props.fetchC(this.props.b_id);
    }
  }

  render() {
    return <framework />
  }
}

Upvotes: 1

Related Questions