React Router: Transition without window.location - reactjs

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);

Related

Push state without retriggering component load

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

React router - calling same method outside componentDidMount

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
}

Component Not Re-rendering on clicking of a Link

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

React context not being updated within callback

I am subscribing a user to events using pusher-js, and am having an issue with the information I am passing in the callback not staying updated. I use react router and have a 'location' context on my components.
connect() {
let {pusher, channelName, eventName} = this.props;
let pusher_channel = pusher.subscribe(channelName);
pusher_channel.bind(eventName, () => console.log(this.context.location.pathname));
}
For demonstration purposes I am just console logging the current url pathname the user is on when the event comes through. This component gets loaded and stays loaded when the user loads that application. The problem is that, if a user navigates to another page in the app and an event comes in, the pathname does not reflect the actual page the user is on but rather the page the user was on when they initially loaded the app.
Is there a way to keep the callback updated as to any context or prop changes that have occurred?
Updating Context
Don't do it.
React has an API to update context, but it is fundamentally broken and you should not use it.
Read more.
Use React Router's location descriptors instead.

How to get content of a DOM element without being in the React context

Right now I'm writing a middleware (from Redux) to consume an API and set the fetched data into the state, however, to call the API I need to set the token to get the data, and the token is saved in a field inside a meta tag in the header, like:
<meta name="csrf-token" content="xJ4XRg4YDnxC8WHpdiFh8t5DzOgeCO7UHCfcStgL">
As our application started JQuery, I could use the following code to get the value:
$('meta[name="csrf-token"]').attr('content')
But I'd like to do that without JQuery, just using React.
What would be the best way to do that?
If you are outside React class (Component), you can do the following without worry :
document.querySelector('meta[name="csrf-token"]').content;
If you are inside React class (Component) , this snippet is valuable only after mounting (going from virtual-dom to dom ). Thus, you can call it inside the following methods of component:
componentDidMount
render
componentDidUpdate

Resources