Ahwan
Ahwan

Reputation: 57

Turn URL Object into URl string

So I have a stringified object in my localStorage,

  const stringifiedURLObject = fromLocalStorage 

I tried to JSON.parse that string to normal Url Object. and I want to convert that object into Url string,

  // i want to turn this
  {
    pathname: 'user/[id]'
    query:  {
      mode: 'active'
      id: 'someID'
    }
  }

  // to this
  const normalPathURL = `/user/xxx?mode=active`

Then pass the string to redirect query

  {
    pathname: '/register',
    query: {
      redirect: normalPathURL,
    },
  }

How can i do that?

Upvotes: 2

Views: 2042

Answers (2)

Jacob Eggers
Jacob Eggers

Reputation: 9322

As an update, there's a solution here:

https://github.com/vercel/next.js/discussions/22025

import Router from 'next/router';
import { resolveHref } from 'next/dist/shared/lib/router/router';
// for next 13
// import { resolveHref } from 'next/dist/shared/lib/router/utils/resolve-href'

const exampleRoute = {
    pathname: '/work/[slug]',
    query: { 
        slug: 'project-foo',
    },
};
const [, resolvedAs] = resolveHref(Router, exampleRoute, true);
//       ^-- resulting path as a string

NOTE: when I tested the return type was defined as string for ``resolveHref, but it actually returned string[], so I had to cast it as any

Upvotes: 1

ABDULLOKH MUKHAMMADJONOV
ABDULLOKH MUKHAMMADJONOV

Reputation: 5234

You can do this easily with javascript string templates:

 const parsedObject = {
    pathname: 'user/[id]'
    query:  {
      mode: 'active'
      id: 'someID'
    }
  }

  // to this
  // parsedObject.pathname.split('/')[0] extracts first part of pathname  
  const normalPathURL = `/${parsedObject.pathname.split('/')[0]}/${parsedObject.query.id}?mode=${parsedObject.query.mode}`

Upvotes: 2

Related Questions