I am using Link property of react to goto the same url, But with the diffrent param. But my api is not calling again as i put the api call part in the componentDidMount().On Click of a url my url param change. Below is the code.
componentDidMount(){
let profile_id = window.localStorage.getItem('profile_id');
if(profile_id && profile_id!==''){
this.props.fetchSingleProfile(profile_id)
}
}
First time, api call and data rendered successfully. Below is how i am using Link.
<Link to={this.userId}>Next</Link>
Now on click of link,I am successfully routed to the give url, But as i mentioned "Component is rendering again on successfully routing, But api is not calling again". Is there any thing in react, which is aware of it, my url is changed, Now call the api again.
Note: Can i use any lifecycle method like: componentWillReceiveProps, But i don't want to call the api again.
But my api is not calling again as i put the api call part in the componentDidMount().
You have same route, so the same <Route> is rendered. All nested components stay the same so instead of remounting they are just updated.
You have few possible ways to handle that:
Fetch data not only on componentDidMount but also on componentDidUpdate
Use key to remount component
It cannot be done with just react-router's <Link /> since it is not actually its responsibility
Related
Say on your clickHandler
you do
// url change will cause this component to be dismounted and a new component will mount
history.push(url)
// do some more work
dispatch(someMoreWork())
What happens to the code after the push call? is the code guaranteed to run?
history navigation is done only after the sync action within the event queue in javascript are executed.
In your case, javascript will executed all the things within the function where you call history.push and will then navigate to the new Route and it will be a predictable behaviour
You can simply validate the above by executing the dispatch action and then accessing the value in the rendered component.
Check this demo that demonstrates the above behavior by dispatching an action after history.push and accessing the resultant redux state in the rendered route
Lets say I have only one component which fetches some data on being mounted.
I want to be able to change the url (pushState) once the component fetches that data however I dont want to change anything on the page or re-render the component.
Let's say I have a route '/' and it loads a which fetches searched contents on load. Once the data is fetched, I want to be able to update the url to say /searchterm
I am looking to do something similar to
window.history.pushState(null, null, '/searchterm') where the url is updated but nothing on the page changes.
Tried using with state and using this.props.history.push
You could store the route in your state, and then memoize the component with a function that returns true if the route changes, which will prevent an update. If you're still using class components, you can implement similar functionality using shouldComponentUpdate
I have a React application where pages are linked using React router. The user is provided with several links. Each link is handled through the router.
All of the corresponding pages have similar logic before render function, so I used a URL parameter, a single Route path, and the same target component. The URL parameter is supposed to be passed to the backend service.
Since the target component is the same and only distinguishing factor is the URL parameter, once the component is rendered for any of the links, the lifecycle methods like componentWillMount, componentDidMount do not execute again. So, even if I click on another link whatever is the state created by the first hit, same is used for other links. REST call is within componentDidMount. Am I missing something?
<Route path="/location/:locationType" component={MapSelectedLocation}/>
MapSelectedLocation is supposed to handle several locationType and invoke REST service based on that.
The expected result is to execute the same code for different locationType. How can I achieve this?
You need to use componentDidUpdate lifecycle method to do the calculation or each props/state change. Put the check in this method and compare the prevProps and new props value.
Also this method will not get called on initial rendering
Like this:
componentDidMount() {
this.doCalculation();
}
componentDidUpdate(prevProps) {
if(this.props.match.params.locationType != prevProps.match.params.locationType) {
this.doCalculation()
}
}
doCalculation() {
// do the calculation here
}
The use case is that I want to map the root (/) to one of two different components based on whether the user is logged in or not, and I want these two components to reside in different bundles and lazily loaded, so simply putting the login check in the render() method would not do.
I tried to use dynamic route definition with require.ensure() to lazily load the component, and it works for the first time, but after changing the login state the component doesn't get updated (even if I navigate to another route and back to / ).
I tried to force re-rendering the router by setting props on the component that contains the router, both manually and by making it a Redux connected component, and I also tried to add a listener to the Redux store and change the component state in response to login change, but in all of the attempts I got the error "You cannot change ; it will be ignored" and the component doesn't change.
My ugly solution is to have the different component loading code outside of the router, listen to the login state change and in response load the matching component and set it in the wrapping component's state, which is referenced in the render() code. Is there a clean "React-Router-ish" way to do what I want?
React Router 4 pretty much solves this as it made the route configuration part of the component rendering, so having conditional rendering is the same whether it's based on the location or on other props/state.
The closest thing to a clean "React-Router-ish" way to do that is to use the React Router Enterhooks.
An enter hook is a user-defined function that is called when a route is about to be rendered. It receives the next router state as its first argument. The replace function may be used to trigger a transition to a different URL.
So, use the onEnter(nextState, replace, callback?) attribute on your <Route />.
Called when a route is about to be entered. It provides the next router state and a function to redirect to another path. this will be the route instance that triggered the hook.
If callback is listed as a 3rd argument, this hook will run asynchronously, and the transition will block until callback is called.
The general best practice I follow is to place the auth-check flow away from your routes, and place it inside the transition events/hooks.
The usual behavior is - before the route handler actually gets rendered, check the auth, and redirect the user to another route. In your case, if you want to use the same route, but render different components - you should be able to do that using the same technique too. However, that's not a common thing (based on what I've seen), but it should be possible.
For a complete example of this approach, here's the auth-flow code example you can check. It is shared by the creators of React Router, so it looks credible to me.
PS: My answer is valid for React Router versions > 0.13.x.
I have an application that uses React Router. The application creates a new item by calling the createPage action, which calls my RefluxJS store and makes a call to an API endpoint. Once that API call returns and is successful I pass the new page object to the pageCreated action. Within my onChanged even in the JSX file I want to transition to a route based on a property of the page without refreshing the page, but I am at a loss on how to do it.
I want to do something similar to window.location = /pages/1234 where 1234 comes from the page object returned by the API.
I have tried Router.transitionTo('/ua-manager/pages/' + options.alias);, but that returns as not a function. How can I achieve this transition without using window.location?
#transitionTo exists on the Router object instance and not the class so access it through this.context.router and it'll work or just add the Navigation mixin.
this.context.router.transitionTo('/ua-manager/pages' + options.alias);