Pass object to query on Router.push NextJs

Viewed 4943

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

1 Answers
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)
}
Related