Reputation: 205
I got an error:
Invalid href passed to next/router: /users//posts, repeated forward slashes (//) or backlashes \ are not valid in the href
I understand why this is happening
handleClick = () => {
// some code
router.push(`/users/${userId}/posts`)
}
userId
is asynchronousely fetched so it doesn't exist during the compilation causing router.push('/users//posts')
. However, this code is inside handleClick
which is triggered on button click.
How do i resolve this?
Upvotes: 2
Views: 6469
Reputation: 1
Try below code
You should remove /
it is between users
and ${userId}
.
handleClick = () => {
router.push(`/users${userId}/posts`)
}
Upvotes: -1
Reputation: 205
It actually wasn't about router.push()
But my navbar. Problem was that my navbar's href was /users/[userId]/posts
and userId
wans't filled out
Upvotes: 2
Reputation: 2504
If userId
is fetched asynchronously, then what the function and component which calls that function look like?
You have the router.push
function in handleClick
function, then I guess you need to pass a parameter for the userId
.
<SomeComponent onClick={() => handleClick(userId)} />
And the function looks like:
const handleClick = (userId) => {
router.push(`/users/${userId}/posts`);
};
Upvotes: 0
Reputation: 2066
handleClick = () => {
// some code
//check link you are pushing
console.log(`/users/${userId}/posts`)
//router.push(`/users/${userId}/posts`)
}
You can't have //
in your link, debug the {userId}
, think it's undefined, it's why error appears.
P.S. If userId
is async, put if condition
before router.push
Upvotes: 0