2

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?

4
  • Do you have any control over the pattern of the param? meaning the bracket syntax. something like a : is a bit cleaner. Regardless I would have a route helper to handle this functionality for you Commented Oct 29, 2021 at 4:29
  • @JohnRuddell i dont know. i'm just following this example nextjs.org/docs/api-reference/next/router#with-url-object Commented Oct 29, 2021 at 4:41
  • 1
    ok, thats fine. What I would do here is probably create a helper that converts the object to an actual URL so you can do whatever you'd like with it from there Commented Oct 29, 2021 at 4:43
  • On my way, thanks! Commented Oct 29, 2021 at 4:44

2 Answers 2

2

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}`
Sign up to request clarification or add additional context in comments.

1 Comment

thank you. i'm thinking the same way. i just wondering if there is another way
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.