How to pass state between routes in NEXT JS? - javascript

I have a data inside an object in my page. I want to redirect from that page to another page along with the data like the code below
const redirectAppointmentStep1 = (value) => {
router.push({
pathname: '/Appointment/bookingstep1',
query: {value : value},
})
}
and I received that data in bookingstep1 page like this
const {query} = useRouter()
but the problem is the query appear on the url and the url does not look clean. How can I send the data from one page to another page but without appearing it on the url?
I am new in Next.js so any help will be highly appreciated.

If you want to send "route state" you have to do it via query string, but you can actually "mask" the path that is shown in the browser via the as property.
Router.push
router.push(url, as, options)
as - Optional decorator for the URL that will be shown in the
browser.
You can decorate the URL to match the path name.
const redirectAppointmentStep1 = (value) => {
router.push(
{
pathname: '/Appointment/bookingstep1',
query: {value : value},
},
'/Appointment/bookingstep1', // "as" argument
)
}

Related

Next.js - On Shallow routing for dynamic path it is removing the basePath from browser url

i have a dynamic routes:
Pages
- [name]
- [brandid]
the browser url should base [basePath]/[name]/[brandid]. After doing shallow routing
router.push("?page=2", undefined, { shallow: true });
the url removes the basePath. And only shows /[name]/[brandid]
When you have dynamic routing in Next.js, and want to do a shallow adjustment of the route to reflect updated query params, you probably want to do something like this:
const router = useRouter()
const url = {
pathname: router.pathname,
query: { ...router.query, page: 2 }
}
router.push(url, undefined, { shallow: true })
This will retreive the current path (router.pathname) and query (router.query) details, and merge them in along with your new page query param. If your forget to merge in the existing query params you might see an error like:
The provided href value is missing query values to be interpolated
properly

Get parameter from URL in Vue JS

I am working on SPA (Vue JS) and Laravel as API. I want when users will receive email to click on button that will sent them to specific route (already implemented).
So now i am struggling how to get the user id from the Vue JS part.
https://domain.test/admin/users/dashboard/user/65/show
65 from the URL is the user ID, so any idea how to extract that ID with java script from Vue JS?
I am not using vue router, this is Laravel route and Vue JS component is rendered from blade file.
I have implemented something like this bellow, but client refused...
https://domain.test/admin/users/dashboard/user/show?userId=65
let id = window.location.href.split('/').slice(-2)[0]
Since you're already rendering the page in a Blade file, you should already have access to the user ID server side.
In that case, simply add the variable server side. For example:
<a :href="'https://domain.test/admin/users/dashboard/user/' + {{
$user->id }} + '/show'">Go to Dashboard</a>
To get parmeters from url you can use vue router for that like this:
const routes = [
// dynamic segments start with a colon
{ path: '/users/:id', component: User },
]
const User = {
template: '<div>User {{ $route.params.id }}</div>',
}
Here is the link for more examples and vue router documentation:
https://router.vuejs.org/guide/essentials/dynamic-matching.html
You can also get parameters with only vanilla JavaScripe like follow:
const queryString = window.location.search;
console.log(queryString);
// ?product=shirt&color=blue&newuser&size=m
//then you have to parse the url
const urlParams = new URLSearchParams(queryString);
const color = urlParams.get('color')
console.log(color);
// blue

Pass parameter to Express controller from button click

Preface: I am writing a Web App using Node.js, Express, and MongoDB.
When a button is clicked I am trying to pass a parameter via URL from my index.ejs to the Express controller ItemController.js in order to dynamically create a filtered set of data.
The button is defined within index.ejs as follows:
<button type="button" class="btn btn-primary" value="/items/items" onclick="loadItems(value, 'Scripting Languages')">
Scripting Languages
</button>
In my external Javascripts file which houses miscellaneous functions, loadItems executes the following:
function loadItems(page, subcategory) {
window.history.replaceState({}, '', "?subcat=" + subcategory); //set URL Param
$('#mainContent').load(page); //load item listing page into grid within HTML GridLayout
}
After this, the router/controller handles the data filtering and page rendering:
Router (item.js)
...
// Get all items
router.get('/items', item.items);
...
Controller (ItemController.js)
...
// loads item listings
itemController.items = function(req, res) {
Item.find({}).exec(function (err, items) {
if (err) {
console.log("Error:", err);
}
else {
var URLSubcat = "Scripting Languages"; //this variable needs to change
var filtered = items.filter(function(el) {
return el.subcategory === URLSubcat;
});
res.render("../views/items/items", {items: filtered});
}
});
};
...
I have tried using req.query.subcat in order to try and grab the parameter from the URL, however it comes back as undefined. I have also tried the techniques in the links below to no avail. What should I be doing to accomplish this? Is there a better way to go about this?
Previously Tried
How to get GET (query string) variables in Express.js on Node.js?
How to access the GET parameters after "?" in Express?
$('#mainContent').load(page);
The URL you are requesting is stored in the page variable.
loadItems(page, subcategory)
… which is defined as an argument
onclick="loadItems(value, 'Scripting Languages')"
… which is passed from the onclick event handler
value="/items/items"
… which gets it value from that attribute.
The query string doesn't show up because the URL you are requesting does not include a query string!
The only query string you have is from here:
window.history.replaceState({}, '', "?subcat=" + subcategory);
… which modifies the URL in the browser addressbar and history without actually requesting it.

Angular not able to get full url

requirement: need to hit the url
localhost:4200/keyone=valueone&keytwo=value2109808329csdc0qwd&keythree=xyz#pqr.com
then capture:
[keyone=valueone, keytwo=value2109808329csdc0qwd, keythree=xyz#pqr.com];
When I am hitting the url using angular 5 its changing to
localhost:4200/keyone
I am not getting the full url. Its disappearing from the = .
Added a path and attached the required info as an id.
ex.
localhost:4200/item?keyone=valueone&keytwo=value2109808329csdc0qwd&keythree=xyz#pqr.com
And got the url values in windows.location.url
/item?keyone=valueone&keytwo=value2109808329csdc0qwd&keythree=xyz#pqr.com
The url looks fine and you should get into a url routed page which is mapped to this irl. As I guess there are no routing available to the url you are providing, its redirecting to a one it found
Normally in angular we catch url params in below way
const routes: Routes = [{
path: ':keyone/:keytwo/:keythree',
component: SomeComponent,
resolve: {
resolvedData: SomeResolverService,
}
}
And then in your resolver or component you can get them by
// inject ActivatedRouteSnapshot
route: ActivatedRouteSnapshot
Then get the params
route.params.keyone, route.params.keytwo, route.params.keythree,

Using Slugs in Meteor's Iron Router

I'm trying to define an Iron Router route to use a slug: ie. a string title but with spaces replaced by hyphens.
Instead of /news/breaking%20news, we want it to be /news/breaking-news.
Router.map(function() {
this.route('news', {
path: '/news/:title'
})
})
To achieve this, do we need to create a new document field slug with the slug string and use path: '/news/:slug? Or is there a more elegant method that avoids this redundant field?
App is using packages aldeed:simple-schema, aldeed:collection2 and dburles:collection-helpers if those help.
The constraining issue is the 1-way, non-reversible transformation from the actual title to the slug (e.g., "foo-bar" and "foo bar" both end up with the same slug, "foo-bar", so when you see "foo-bar" you don't know what the actual title is, so you can't look it up). So unless you can control for that (e.g., adding the slug to the document as you suggest, or enforcing a strict no-hyphens policy for titles in the application), you'll need a way to store the mapping.
One potential way around this would be to include the document ID in the URL and have a meaningless slug, which can be filled in by the router itself:
Router.route('/news/:_id/:slug?', ...)
Then only use the _id in the actual routing. Note that this allows you to put whatever you want in the URL after the _id, so that 'news/[_id]/foo-bar' and 'news/_id/foo%20bar' both go to the same page, (news/[_id]), but so does 'news/[_id]/this_is_completely_meaningless.' In the router, you can then redirect to the appropriate URL as needed:
Router.route('/news/:_id/:slug?', {
name: 'news',
data: function() { return news.findOne({_id: this.params._id}); },
onBeforeAction: function() {
var data = this.data();
if (data) {
var realUrl = '/' + data._id + '/' + slugify(data.title); // the desired URL, incl. whatever your slug fn is
if (this.url.indexOf(realUrl) < 0) {
this.redirect('/news' + realUrl); // if we aren't at the desired URL, take us there
}
}
this.next();
}
});
You'd then have to control for any "share this page" functionality to ensure that it gives the desired URL, but if anyone tries to go to news/[_id]/this_is_completely_meaningless it'll redirect them to news/[_id]/foo-bar.

Categories

Resources