Reputation: 855
I am new to react-router
and right now I have following routes in my app:
<Router history={browserHistory}>
<Route path="/" component={MainLayout}>
<Route path="/v/:username/:reponame/:page/:perPage" component={Results} />
</Route>
</Router>
As you can see, there's a MainLayout component that includes an <input type="text">
which is used to connect to Github API and retrieve list of issues for a certain repo.
Then the Results
component steps in. Here's the code for it's componentDidMount()
:
componentDidMount() {
const {
username,
reponame,
page,
perPage
} = this.props.params;
this.sendRequest(username, reponame, page, perPage);
}
sendRequests
essentially contains the ajax query for fetching the output data, after which it's being set into the component's state:
this.state = {
data: [], // here
lastPage: -1,
errorMessage: ''
}
Now this works pretty well till the very moment when one wants to change the value of an input
.
As I see, the Result
component doesn't unmount. Instead, it invokes componentWillReceiveProps()
and updates the existing component. AFAIK it is safe to perform side calls in componentDidUpdate()
so I just copied the code above from componentDidMount()
and pasted it in there. This way, though (and it is absolutely reasonable) componentDidMount()
is being invoked over and over again.
The only workaround I came up with at the moment is comparing old and new data in the sendRequest()
itself and invoke setState()
inside of it only if it differs via deep-equal
package, so it looks like this:
if (!equal(res, this.state.data)) {
this.setState({
...this.state,
data: res,
lastPage
});
}
Is this considered to be an ok pattern or there is a better way to solve this issue?
Upvotes: 0
Views: 676
Reputation: 554
You should not use setState inside the cDM lifecycle. as it might trigger re-render, which will cause your infinite loop.
Updating the state after a component mount will trigger a second render() call and can lead to property/layout thrashing.
https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md
Upvotes: 1