I’m building an app with React using Next.js. I want to pass userId
along with the router push and use the userId
in the Component which I have pushed to.
See the below code:
import { useRouter } from "next/router";
import styles from "./postcard.module.css";
const PostCard = (props) => {
const router = useRouter()
return (
<div className={styles.post}>
<div className={styles.userDetails}
onClick={()=>{router.push(`/user/${props.user._id}`)}} >
</div>
</div>
);
};
export default PostCard;
The above code will redirect to /user/:id
page; which is used to load profile details.
In the /user/:id
page, the below function is used to retrieve the user id from local storage which is stored at the time of login.
const getUserData = async () => {
const userId = getUser()
const res = await instance.get(`/user/${userId}`)
setUser(res.data)
}
When the /user/:id
page is loaded from the Postcard component, I want to replace userId
with props.user._id
. I don’t haveany idea to do it. Please help.
2
Answers
You can use router.query in your profile component.
You seem to have used React Router Dom to set up your routes. If so, here is you would get the id on the destination page:
But if you have used the Next.js way, and assuming the file you are redirecting to is called
[id].js
or[id].tsx
, you would get the passed id like so: