Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is componentDidMount the best place to fire AJAX request

A common use case is seen at lots of react projects that the AJAX request is fired at componentDidMount hook.

I just can't wrap my head around this proposed practice , let's say we have below component where the AJAX request depends on a prop from parent component and MyComponent won't get properly updated with correct ajax data if a second render action triggered from it's parent component(with new props) happen.but componentDidMount won't get executed anyway

so I think this practice is gonna cause issue , can anyone help confirm it and justify it? or correct me if I'm wrong.

export default class MyComponent extends Component {
  constructor() {
    super(...arguments);
  }
  
  async componentDidMount() {
    const data = await fireAjax(this.props.id);
    this.setState({data});
  }

  render() {
    const { data } = this.state;
    return (
        { data && <span>{data}</span> }
    );
  }
}
like image 340
Deng Zhebin Avatar asked Mar 13 '18 16:03

Deng Zhebin


1 Answers

You're misunderstanding the pattern.

componentDidMount is the correct place to do async fetching that you want to occur when the component mounts. If there is some other action that ought to trigger the data fetch, then yeah, do the async call in that other location.

What you really want to look into is the entire Flux paradigm, which is a fully fleshed out data flow made for react (though it can also be used elsewhere). There are plenty of packages that wrap that design pattern with helpful handlers, the most popular being Redux.

But no, no one is suggesting that all async calls occur in that lifecycle hook.

like image 186
Jake Haller-Roby Avatar answered Nov 19 '22 05:11

Jake Haller-Roby