Fail to use history.replaceState in next.js - reactjs

I export Next.js as static files and let backend code handle them. What I need is just to remove query params in the current URL. I used to use
window.history.replaceState(null, null, window.location.pathname)
When there are no query params, replaceState works, but when query params exist, soon the url is changed back. What is causing this?
I am using a custom server, so 'next/router' doesn't help, it only reload the page.
Here is an example,
suppose my current path is /home, I can call window.history.replaceState(null, null, '/home1') to change path to /home1. But if path is like /home?a=123, after replaceState is called, the url revert to /home?a=123 right away.

Related

How add ability add query params for gatsby routes?

How to generate pages in gatsby that will allow you to add parameters to the routing like https://page1?someParam=param or https://page1/param
What I mean? When we navigate to page page1 in gatsby it work's fine, but what if I just want add uniq params for page for google analitics? so for this I want to have ability
add some additional params for the page from where I made redirect, but when I add
for page1 some params like https://page1?someParam=param or https://page1/param, it updated and show me just https://page1 instead.
I suppose that it's related to way how I created pages. Here is my code:
createPage({
path: `${localePrefix}/${slug}`, // so should I change it here in order to work as needed?
component: PageTemplate,
context: {
...context,
localizedPaths,
},
})
Can it be fixed with?
matchPath: path: ${localePrefix}/${slug}?*,
matchPath: path: ${localePrefix}/${slug}/*,
Recap:
My question is about why gatsby remove query params from pages?
https://some_site/some_page?some_param=323
translates into
https://some_site/some_page
https://page1?someParam=param or https://page1/param are not the same. While a query parameter (first case: ?someParam=param) is an optional value that doesn't change the rendered page (it doesn't point to any specific route hence it's not requesting any file). The second one (https://page1/param) is accessing a /pages/param route.
Since they are URL parameters, you don't need to change anything in your project, you just need to catch them using JavaScript. They are handled in thee:
const urlParams = new URLSearchParams(window?.location?.search);
Note: you can access directly location prop in Gatsby
If your project is replacing https://some_site/some_page?some_param=323 to https://some_site/some_page it's because some server-side configuration or a CDN, not because of Gatsby's behavior, like any other React project.

How to programmatically (and idiomatically) navigate to an external URL?

I am working on a React microservice. At some point we verify the user data to have a certain value, otherwise we want to redirect to an external URL. That sounds easy, but I am not sure if my current solution is idiomatically correct.
React router doesn'T seem to provide anything beyond the current domain. I can only change the path, using the history object. Is there something I overlooked?
I am using window.location.href now to get the current URL, as I need to pass this as a callback, and window.location=xyz to navigate. but it feels wrong.
// ComponentX.js
...
if (name === null) {
window.location = selectOrgURL(window.location.href);
}
render (
...

React-redux get site base URL / window.location

Hopefully this is a very simple question:
I want to create a string containing the full URL to a page on my site, like:
https://example.com/documents/1
Ideally I'd like to generate this in a react-redux connect()-ed container, in mapStateToProps(). Where the page is a grandchild of a react-router Route using browserHistory (so maybe I can get it from react-router or browserHistory somehow?) If necessary I'd do it in a full-on React class.
But I can't for the life of me find out how to do this. window (as in window.location) is always undefined in mapStateToProps() (no big surprise there) and in my view components' render() function.
So far I have only found ways to access the current route, e.g. "/documents/1", which is only a relative path and does not contain the site base url (https://example.com/)
So firstly, remember your code runs on client and server so any access to window needs to be wrapped in a check.
if (typeof window !== 'undefined') {
var path = location.protocol + '//' + location.host + '/someting'; // (or whatever)
} else {
// work out what you want to do server-side...
}
If the URL you generate shows in the DOM, and on the client you populate the store with this URL before the first render, you're going to get a checksum error. If you really want to avoid the error you can wait until componentDidMount() in your root component to get/set the url.
After componentDidMount you can have direct access to the origin location so that you can get the root url.
I use the below code in my JSX all the time so that i dont have to worry about the root path ex: dev env this would be localhost:3000/whatever, staging this will be AppStaging.heroku/whatever/..... and in production it would evaluate to www.myapp.com/whatever
`${window.location.origin.toString()}/whateverRoute/`
You Can try!!
window.location.origin
you can try the URL API. Take a look at this link for more details https://developer.mozilla.org/en-US/docs/Web/API/URL
const url = new URL("blob:https://mozilla.org:443/")
console.log(url.origin);
// Logs 'https://mozilla.org'

how to check base url before routing using router in backbone.js

I am new to backbone.js, pardon me if the question seems silly.
I am routing to other pages using :
this.options.app.navigate( myNewURL, true);
this myNewURL gets appended to the current URL in the window but before doing that i want to make some checks on it.How do i fetch the current url and then append the newUrl to it and redirect?
eg:
current url : abc.com/firstString/SecondString
on navigation i want : abc.com/SecongString/myNewUrl
this firstString might or might not exist, so i have to make a check for it and remove it before redirection.
How can that be done?
The way I prefer navigation in Backbone.
Backbone.history.navigate('myNewUrl',{trigger:true}); //This will fire the router
Make trigger false to just change the route, but not execute the router.
In order to get the current url, you can use
Backbone.history.fragment();
References :
http://backbonejs.org/docs/backbone.html

Backbone Router confusion on howto trigger

I can't seem to get the Backbone Router working in an expected manner. I i) instantiate my Router, then ii) call Backbone.history.start( { pushState: true, root: '/' } ). With the code below...
1) going to "/dashboard" or "/grid", the defined functions are not called
2) when I invoke myrouter.navigate("grid"), the defined functions are not called
**) However, if I then go back or forwards throught the history, then the defined functions are called.
Router : Backbone.Router.extend
routes:
"dashboard": "dashboard"
"grid/:storyid": "grid"
dashboard: ->
console.log("...")
grid: (storyid) ->
console.log("...")
What do I need to do to get cases 1) and 2) to work?
Thanks
Your router is working exactly as it's supposed to. I think your expectations of how it works, and why, are off.
1) going to "/dashboard" or "/grid", the defined functions are not called
When you type "/dashboard" or "/grid" in to your browser's URL bar, your browser makes a request to your server to get that url. This bypasses the router because the browser is making the request back to the server.
The only time typing a URL in to the browser's URL input would not request a new page from the server, is when you are only modifying the hash fragment: "#whatever".
when I invoke myrouter.navigate("grid"), the defined functions are not called
The default behavior of router.navigate is to update the URL w/ the appropriate route, but not that route to be handled by the router - exactly what you are describing.
If you want to force the browser to process the route change, pass true as a second argument: myrouter.navigate("grid", true)
**) However, if I then go back or forwards throught the history, then the defined functions are called.
This works because the router has registered itself w/ the browsers history API and is given the opportunity to handle the URL changes that are caused by the fwd / back buttons, before the browser goes back to the server to get the requested URL.

Resources