Leon Leon - 11 months ago 82
React JSX Question

Track only one state React

The issue I've encountered is an infinite loop.

I have this state:

this.state = {
apiData: [],
pageNum: 1,
isLoadingList: 0,
search: "",
layout: "list"

I have a function that fetch data from an API:

fetch("www.api.com", ...)

And once the data fetched, it saves everything in apiData (this.state.apiData)

The thing I'm trying to do is to call that function, "fetchApi()", when "this.state.search" changes. If I do that using Lifecycle's components like componentDidUpdate(), ... it will create an infinite loop as apiData is a state too (the changes made to this.state.apiData will trigger Lifecycle's components related to states again, and again, and ...).

So I would like to track ONLY this.state.search and when it changes it calls the function "fetchApi()" that change this.state.apiData value.

I might trying to do something that is wrong and shouldn't be done like that, so any ideas to do the same thing but in a different way are welcome.


leo leo
Answer Source

Use shouldComponentUpdate

shouldComponentUpdate: function(nextProps, nextState) {
  return this.state.search !== nextState.state.search;