R
R
R-Oscar2017-03-23 17:04:42
React
R-Oscar, 2017-03-23 17:04:42

How to properly execute ajax requests in react-router?

Using react-router v3
Let's say we have a component that makes get requests based on the parameters passed in the URL.
Where should the request be located? If you put it in componentDidMount()and componentDidUpdate(), the latter will be fired in a loop (which is quite logical, since the result of the request is placed in the state of the component, which causes the next update).
I also tried to use a property onEnteron the route ( documentation ), but it nextStateturned out to be an immutable object, so the result from the request is not transferred to the component.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Islam Ibakaev, 2017-03-24
@R-Oscar

componentDidUpdate(prevProps){
    props.params.id !== prevProps.params.id && dispatch(fetchData());
}

I
Ivan, 2017-03-23
@LiguidCool

I use the call in componentWillMount(), or in the constructor. Well, this is where you might be able to help.

M
Maxim, 2017-03-23
@maxfarseer

The request must be in either componentDidMount or componentWillMount.
Why do you need componentDidUpdate?
PS Recently I was asked the same thing, and if your problem is that componentDidMount does not "occur" when the route parameter changes, then here you need to use componentWIllReceiveProps(!)
Example: <Route path='/articles/:id' >
You open the browser at the URL: /articles/1
You have a call in componentDidMount ( For example:getArticles(this.props.params.id)
Then you click the link, change the URL to /articles/2 and wait for componentDidMount to happen? No, it won't, because the route ('/articles/:id') hasn't changed, hence there was no "unmount" or "unmount" of the component. But there was a "props change" in the component (of the same this.props.params.id), so this can be handled in componentWillReceiveProps

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question