Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 554
kivul Avatar asked Mar 01 '20 05:03

kivul


People also ask

How do I pass props with my next router?

There is no way to pass data between pages with Next's router. You would have to either use query strings as you mentioned, sessionStorage, or a state management option like Redux or React's Context API. You could then put that in your pages/_app.

How do I get a router query in next JS?

Method 2: Using withRouter() Method: You can easily get the current router value in react class component using the withRouter(). To use this you just have to export your class component inside withRouter().

What is NextPage in NextJS?

NextPage is a type exported by NextJS. When we write Page: NextPage we're saying that our Page component is of type NextPage . Follow this answer to receive notifications.


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)
}
like image 182
Pushp Singh Avatar answered Sep 21 '22 16:09

Pushp Singh