kivul
kivul

Reputation: 1158

Pass object to query on Router.push NextJs

Im new to NextJs and im trying to pass an object to another page through a component. I'll post the code and explain better what im trying to do:

The object is like this:

objectEx = {
  name: 'name',
  description: 'description'
}

This is the main component: Im trying to pass the object in the Router.push

export default class ComponentDummy extends Component {

  handleSubmit = value => e => {
    e.preventDefault()
    Router.push({
      pathname: '/OtherPage'
      query: { **PASS AN OBJECT HERE** } //what im trying is: query: { objectEx: objectEx},
    }
  }
}

This is the page that im trying to receive the object in query

const OtherPage = ({ query }) => {
  return( 
    <div> 
      Do Stuff with the object here
    </div>
  )
}

OtherPage.getInitialProps = ({ query }) => {
  return { query }
}

Then on the page above im trying to access the object like:

query.objectEx.name

This is not working as I thought I would. How can I achieve that?

Thanks in advance

Upvotes: 11

Views: 7355

Answers (2)

Kęstutis
Kęstutis

Reputation: 545

You are not allowed to pass Object as query param for next/router. You need to pass string

Router.push({
   pathname: '/OtherPage'
   query: { objectEx: JSON.stringify(objectEx) },
}

Keep in mind, that you'll need to parse it your self

const params = JSON.parse(decodeURIComponent(router.query.objectEx))

Better yet to use lib like qs for stringifying objects to URL params.

Upvotes: 1

Pushp Singh
Pushp Singh

Reputation: 596

Well, first thing is you passed object as a query param.

Router.push({
      pathname: '/OtherPage'
      query: { data: objectEx} 
    }

So, in order to access the object in the OtherPage, you need to fetch this inside componentDidMount.

componentDidMount() {
let data = window.location.search;
console.log(data)
}

Upvotes: 6

Related Questions