Skip to content Skip to sidebar Skip to footer

Api Call On Event In React, Componentdidupdate Or Eventhandler?

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) => (eve

Solution 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));
}

Solution 2:

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: IfrequestDataActionDispatch 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...)

Solution 3:

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)

Post a Comment for "Api Call On Event In React, Componentdidupdate Or Eventhandler?"