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
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.
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().
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With