skip to Main Content

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


  1. You can use router.query in your profile component.

    const router = useRouter();
    
    useEffect(() => {
      console.log(router.query);
    }, [router.query]);
    
    Login or Signup to reply.
  2. 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);
      };
      //...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search