Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch data when a React component prop changes?

My TranslationDetail component is passed an id upon opening, and based on this an external api call is triggered in the class constructor, receiving data to the state, and this data being displayed on TranslationDetail.

//Routing: <Route path="/translation/:id" component={TranslationDetail}/>  //Class:     class TranslationDetail extends Component {   constructor(props){     super(props);      this.props.fetchTrans(this.props.params.id);   } 

This all works fine if I enter the url manually. In case I'd like to use react-router e.g. for displaying the next item like below the url does change, but the api call is not triggered, and the data will remain the same.

<button    type="button"   onClick={() =>      browserHistory.push(`/translation/${Number(this.props.params.id)+1}`)}>   Next </button> 

Please bear in mind that I'm a total beginner. The reason why this is happening is I believe that the constructor is run only once, thus no further api call is triggered.

How can I solve this? Do I need to listed to props and call a function on change? If yes, how?

like image 860
balu000 Avatar asked Aug 17 '16 15:08

balu000


People also ask

What happens when props change React?

React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.

Can props update value in React?

A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.

Does useEffect run when props change?

In this case, the side effect will run every time there is a change to the props passed as a dependency. useEffect(() => { // Side Effect }, [props]);


Video Answer


1 Answers

Constructor is not a right place to make API calls.

You need to use lifecycle events:

  • componentDidMount to run the initial fetch.
  • componentDidUpdate to make the subsequent calls.

Make sure to compare the props with the previous props in componentDidUpdate to avoid fetching if the specific prop you care about hasn't changed.

class TranslationDetail extends Component {        componentDidMount() {      this.fetchTrans();    }     componentDidUpdate(prevProps) {      if (prevProps.params.id !== this.props.params.id) {        this.fetchTrans();      }    }     fetchTrans() {      this.props.fetchTrans(this.props.params.id);    } } 
like image 122
Yury Tarabanko Avatar answered Oct 01 '22 17:10

Yury Tarabanko