2

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 localStorage 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 have any idea to do it.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181

2 Answers2

1

You can use router.query in your profile component.

const router = useRouter();

useEffect(() => {
  console.log(router.query);
}, [router.query]);
astro62
  • 51
  • 4
1

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:

import { useParams } from "react-router-dom";

export default function UserDetail() {
  const params = useParams();

  const getUserData = async () => {
    const userId = params.id;
    const res = await instance.get(`/user/${userId}`);
    setUser(res.data);
  };
  //...
}

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:

import { useRouter } from "next/router";

export default function UserDetail() {
  const router = useRouter();

  const getUserData = async () => {
    const userId = router.query.id;
    const res = await instance.get(`/user/${userId}`);
    setUser(res.data);
  };
  //...
}
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
  • This code works. But when user wants to view his own profile, i want to get user id from local storage; which saved at the time of login. I tried to set userId using if condition. If user.query.id == true setUserId(router.query.id) else userId = getUser(). But since there is a delay in getting data from router, my code is getting messed up – Unnikrishnan KJ Aug 14 '23 at 16:34
  • 1
    Glad it did. Since it's a kinda new issue, I would suggest you create a new question with all the code you have in the user detail component and paste its link here. I would be happy to answer it. – Youssouf Oumar Aug 14 '23 at 16:51
  • Thanks @YoussoufOumar, please check the link : https://stackoverflow.com/q/76900915/21387444 . Hope you have understood my requirement. – Unnikrishnan KJ Aug 14 '23 at 17:14