1

Where should we ideally place an api call to be made on occurrence of an event in React

Inside the eventHandler or componentDidUpdate ?

example:

handleItemClick = (item) => (event) => {
  this.setState({selectedItem: item});
  this.props.requestDataActionDispatch(item);
}

OR

componentDidUpdate(prevProps, prevState, snapshot) {
  if(prevState.item !== this.state.item) {
    this.props.requestDataActionDispatch(item);
  }
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Rahul Yadav
  • 2,627
  • 5
  • 30
  • 52

3 Answers3

1

I don't see any reason to wait for component update, I'd just put it in the event handler.

Naturally, in either case your component needs to know how to render appropriately when it has a selected item but doesn't have the data from the API yet...


(Side note: If requestDataActionDispatch results in a state change in your component, you probably want to clear that state when setting the selected item prior to the request, so you don't have one item selected but still have the state related to the previous item. But I'm guessing from the fact it's on props that it doesn't...)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Depends

But a simple solution is, if you want to call some API after change of state value then you must go for eventHandler. Also check for callback in setState.

handleItemClick = (item) => (event) => {
  this.setState({selectedItem: item}, () => this.props.requestData(item));
}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59
0

It depends

I would prefer to call the api inside componentDidUpdate. Why ? Because it's cleaner. Whenever there is a change in state or props, componentDidUpdate will be called. So definitely, there has to be a condition inside componentDidUpdate like you have mentioned

if(prevState.item !== this.state.item)